//
//  DualMediationSDKPublic.m
//  DualMediationSDK
//
//  对外公开接口实现 - 简洁版
//

#import "DualMediationSDKPublic.h"
#import <UIKit/UIKit.h>
#import "Core/DMComplianceManager.h"
#import "Utils/Logger/IMLogUtils.h"
#import "Utils/IMUtilsManager.h"
#import "API/Login/IMLoginService.h"
#import "API/AdStrategy/IMAdStrategyService.h"
#import "API/GameStrategy/IMGameStrategyService.h"
#import "API/Firebase/IMFCMService.h"
#import "API/Firebase/DMFirebaseManager.h"
#import "API/HTTP/YKHTTPService.h"
#import "API/Device/IMDeviceInfoService.h"
#import "API/Firebase/IMFCMPushService.h"
#import "API/Vibrate/IMVibrateService.h"
#import "API/Vibrate/IMVibrateModels.h"
#import "API/Base/IMAPIManager.h"
#import "Utils/Device/IMKeychainUUIDManager.h"
#import "Utils/JSON/DMConfigReader.h"
#import "API/AdStrategy/IMAdStrategyManager.h"
#import "API/AdStrategy/IMSDKStartupConfigManager.h"
#import "API/TA/DMThinkingManager.h"
#import "AD/DMBannerScenes.h"
#import "AD/IronSource/DMIronsourceManager.h"
#import "AD/IronSource/DMRewardedVideoManager.h"
#import "AD/IronSource/DMInterstitialManager.h"
#import "AD/IronSource/DMBannerManager.h"
#import "AD/IronSource/DMNativeAdManager.h"
#import "AD/MAX/DualMediationMAXManager.h"
// 移除内部类引用 - DualMediationMAXSplashManager
#import "AD/MAX/DualMediationMAXRewardedVideoManager.h"
#import "AD/MAX/DualMediationMAXInterstitialManager.h"
#import "AD/MAX/DualMediationMAXBannerManager.h"
#import "AD/MAX/DualMediationMAXNativeADManager.h"
#import "AD/Common/DMBannerSceneManager.h"
#import "AD/Common/DMBannerStrategyParser.h"
#import "AD/Common/DMNativeStrategyParser.h"
#import "DMNativeTypes.h"
#import "DMLifecycleManager.h"
#import "AD/Common/DMAdDelegate.h"
#import "API/Facebook/DMFacebookManager.h"
#import "DMInAppVerifyManager.h"
#import "DMInAppPurchaseManager.h"
#import "API/InAppPurchase/DMProductManager.h"
#import "API/TA/DMThinkingManager.h"
#import "DMAdjustManager.h"
#import "Core/DMAdConfig.h"
#import "RealTimeLogWindow.h"
#import "Utils/LogView/AppInfoViewController.h"
#import "Core/DMLifecycle/Types/DMLifecycleTypes.h"
#import "DMNetworkMonitor.h"

// 仅响应按钮区域触摸的悬浮窗
@interface _DMPassthroughWindow : UIWindow
@property (nonatomic, weak) UIView *hitTestView; // 仅此视图区域可响应，其余触摸透传
@end

@implementation _DMPassthroughWindow
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (self.hidden || self.alpha < 0.01 || !self.userInteractionEnabled) {
        return nil;
    }
    // 仅当触点落在 hitTestView（悬浮按钮）上时才拦截，其余全部透传到底层窗口
    if (self.hitTestView) {
        CGPoint p = [self.hitTestView convertPoint:point fromView:self];
        if ([self.hitTestView pointInside:p withEvent:event]) {
            UIView *v = [self.hitTestView hitTest:p withEvent:event];
            return v ?: self.hitTestView;
        }
    }
    return nil; // 透传
}
@end

@interface DualMediationSDKPublic ()

@property (nonatomic, strong) DMComplianceManager *complianceManager;
@property (nonatomic, assign) BOOL isSDKInitialized;
@property (nonatomic, assign) BOOL isComplianceCompleted;
@property (nonatomic, assign) BOOL debugModeEnabled;
@property (nonatomic, weak) id<DMAdDelegate> adDelegate;

// 免广告状态存储
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *adBanStatusDict;

// 实时日志窗口
@property (nonatomic, strong) RealTimeLogWindow *realTimeLogWindow;

// 实时日志悬浮按钮
@property (nonatomic, strong) _DMPassthroughWindow *floatingLogWindow;
@property (nonatomic, strong) UIButton *floatingLogButton;
@property (nonatomic, assign) CGPoint floatingButtonInitialCenter;

// 私有方法声明
- (void)executeAutoLoginAndStrategyFlow;
- (void)attemptLoginWithUUID:(NSString *)uuid retryCount:(NSInteger)retryCount maxRetries:(NSInteger)maxRetries;
- (void)executeStrategyAPIs;
- (void)applySDKStartupConfigurationFromAdStrategy;
- (void)initializeAdPlatformWithSDKType:(NSString *)sdkType;

@end

@implementation DualMediationSDKPublic

@synthesize adDelegate = _adDelegate;

#pragma mark - 单例实现

+ (DualMediationSDKPublic *)sharedInstance {
    static dispatch_once_t onceToken;
    static DualMediationSDKPublic *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[DualMediationSDKPublic alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 首先初始化日志系统
        [IMUtilsManager initializeUtils];
        
        _complianceManager = [DMComplianceManager sharedManager];
        
        _isSDKInitialized = NO;
        _isComplianceCompleted = NO;
        _debugModeEnabled = NO;
        
        // 初始化免广告状态字典
        _adBanStatusDict = [[NSMutableDictionary alloc] init];
        
        // 从磁盘加载免广告状态
        [self loadAdBanStatusFromDisk];
        
        [IMLogUtils info:IMLogTagSDKInit format:@"DualMediationSDKPublic 初始化完成"];
        
        // 获取单例实例
        DMConfigReader *configReader = [DMConfigReader sharedInstance];

        // 加载配置文件
        BOOL success = [configReader loadConfig];
        if (!success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"❌ 配置加载失败"];
        }
    }
    return self;
}

#pragma mark - 核心接口实现

- (void)initializeSDKWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 开始SDK初始化"];
    
    if (self.isSDKInitialized) {
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ SDK已初始化，直接返回成功"];
        if (completion) completion(YES, nil);
        return;
    }
    
    // 步骤1: 先完成合规初始化
    [self initializeComplianceWithCompletion:^(BOOL complianceSuccess, NSError * _Nullable complianceError) {
        // 使用手动引用计数兼容的方式
        DualMediationSDKPublic *strongSelf = self;
        if (!strongSelf) return;
        
        if (!complianceSuccess) {
            // 合规失败不再阻断SDK初始化，记录并继续
            [IMLogUtils warning:IMLogTagSDKInit format:@"⚠️ 合规初始化失败，继续进行SDK核心初始化：%@", complianceError.localizedDescription];
            // 可按需标记状态供后续逻辑参考
            strongSelf->_isComplianceCompleted = NO;
            
            // 可选：埋点记录合规失败但继续
            if ([[IMSDKStartupConfigManager sharedManager] isAdLoadTrackEnabled]) {
                @try {
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_Init" properties:@{
                            @"w_name": @"DualMediationSDK",
                            @"w_is_success": @(NO),
                            @"w_error_code": @(complianceError.code),
                            @"w_error_msg": complianceError.localizedDescription ?: @"合规初始化失败",
                            @"w_sdk_version": [strongSelf sdkVersion] ?: @""
                        }];
                    });
                } @catch (NSException *exception) {
                    [IMLogUtils error:IMLogTagSDKInit format:@"⚠️ 合规失败埋点异常: %@", exception.reason];
                }
            }
        }
        
        // 步骤2: 合规完成后，继续SDK初始化
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 合规完成，开始SDK核心初始化"];
        
        // 配置HTTP服务
        [YKHTTPService configureWithProductionURL:@"https://sapi.yarkgame.com"
                                           testURL:@"https://sapi.yarkgame.com"
                                           signKey:@"6PDFY2kWBovqMLTu"
                                       gameVersion:[[DMConfigReader sharedInstance]appVersion]
                                        sdkVersion:[[DMConfigReader sharedInstance]sdkVersion]];
        
        // 根据编译模式设置环境
#ifdef DEBUG
        // DEBUG模式：使用测试环境
        [YKHTTPService switchToTest];
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 DEBUG模式：已设置为测试环境"];
#else
        // RELEASE模式：使用正式环境
        [YKHTTPService switchToProduction];
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 RELEASE模式：已设置为正式环境"];
#endif
        
        [IMLogUtils info:IMLogTagSDKInit format:@"🌐 HTTP服务配置完成"];
        
        // 模拟SDK初始化过程
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 设置SDK为已初始化状态
            strongSelf.isSDKInitialized = YES;
            
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ SDK核心初始化完成"];
            
            // SDK初始化完成埋点事件 - 符合事件埋点开发文档规范
            if ([[IMSDKStartupConfigManager sharedManager] isAdLoadTrackEnabled]) {
                @try {
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_Init" properties:@{
                            @"w_name": @"DualMediationSDK",
                            @"w_is_success": @(YES),
                            @"w_error_code": @(0),
                            @"w_error_msg": @"",
                            @"w_sdk_version": [strongSelf sdkVersion] ?: @""
                        }];
                    });
                } @catch (NSException *exception) {
                    [IMLogUtils error:IMLogTagSDKInit format:@"⚠️ SDK初始化埋点异常: %@", exception.reason];
                }
            } else {
                [IMLogUtils info:IMLogTagSDKInit format:@"🔕 SDK初始化埋点已禁用"];
            }
            
            // SDK初始化完成后，自动执行登录和策略流程
            [IMLogUtils info:IMLogTagSDKInit format:@"🚀 SDK初始化完成，开始自动登录和策略流程"];
            [strongSelf executeAutoLoginAndStrategyFlow];
            
            // 调用成功回调
            if (completion) {
                completion(YES, nil);
            }
        });
    }];
}

- (void)initializeComplianceWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagSDKInit format:@"🚀 开始SDK合规初始化"];
    
    if (self.isComplianceCompleted) {
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 合规已完成，直接返回成功"];
        if (completion) completion(YES, nil);
        return;
    }
    
    [self.complianceManager initializeComplianceWithCompletion:^(BOOL success, NSError * _Nullable error) {
        // 使用手动引用计数兼容的方式
        DualMediationSDKPublic *strongSelf = self;
        if (!strongSelf) return;
        
        if (success) {
            strongSelf.isComplianceCompleted = YES;
            [IMLogUtils info:IMLogTagSDKInit format:@"🎉 SDK合规初始化成功"];
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ SDK合规初始化失败: %@", error.localizedDescription];
        }
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(success, error);
            });
        }
    }];
}

#pragma mark - 状态查询

- (BOOL)isSDKInitialized {
    return _isSDKInitialized;
}

- (BOOL)isComplianceCompleted {
    return _isComplianceCompleted;
}

- (NSString *)sdkVersion {
    return @"1.0.0";
}

#pragma mark - 调试功能

- (void)setDebugModeEnabled:(BOOL)enabled {
    _debugModeEnabled = enabled;
    [IMLogUtils info:IMLogTagGeneral format:@"🔧 调试模式: %@", enabled ? @"启用" : @"禁用"];
}

- (BOOL)isDebugModeEnabled {
    return _debugModeEnabled;
}

#pragma mark - 广告代理管理

- (void)setAdDelegate:(nullable id<DMAdDelegate>)delegate {
    _adDelegate = delegate;
    [IMLogUtils info:IMLogTagGeneral format:@"🎯 广告代理已设置: %@", delegate ? @"是" : @"否"];
    
    // 将代理传递给插屏广告管理器
    [DMInterstitialManager shareInterstitialManager].delegate = delegate;
    [DualMediationMAXInterstitialManager sharedInterstitialManager].delegate = delegate;
    
    // 将代理传递给横幅广告管理器
    [DMBannerManager shareBannerManager].delegate = delegate;
    [DualMediationMAXBannerManager sharedBannerManager].delegate = delegate;
    
    // 将代理传递给激励视频管理器
    [DMRewardedVideoManager shareRewardedVideoManager].delegate = delegate;
    [DualMediationMAXRewardedVideoManager sharedRewardedVideoManager].delegate = delegate;
    
    // 开屏广告管理器代理设置已移除（内部实现）
    
    //原生广告管理器代理
    [DualMediationMAXNativeADManager sharedNativeADManager].delegate = delegate;
    [DMNativeAdManager sharedInstance].delegate = delegate;
    
    //苹果内购代理管理器
    [DMInAppPurchaseManager shareInAppPurchaseManager].delegate = delegate;
    [DMProductManager sharedManager].delegate = delegate;
    [DMInAppVerifyManager sharedManager].delegate = delegate;
    
    // 设置合规管理器代理
    self.complianceManager.delegate = delegate;
    
    [IMLogUtils info:IMLogTagGeneral format:@"🎯 代理已传递给所有广告管理器和合规管理器"];
}

- (nullable id<DMAdDelegate>)adDelegate {
    return _adDelegate;
}

#pragma mark - 登录接口

- (void)loginWithAppId:(NSString *)appId
              iosUuid:(NSString *)iosUuid
          countryCode:(NSString * _Nullable)countryCode
           completion:(void(^)(BOOL success, NSDictionary * _Nullable userInfo, NSError * _Nullable error))completion {
    
    [IMLogUtils info:IMLogTagAPI format:@"🔐 开始用户登录"];
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:2001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 登录失败: AppId为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    if (!iosUuid || iosUuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:2002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"iOS UUID不能为空"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 登录失败: iOS UUID为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    // 调用登录服务
    [[IMLoginService sharedService] loginWithAppId:appId
                                           iosUuid:iosUuid
                                       countryCode:countryCode
                                           success:^(IMLoginResponse *response) {
        [IMLogUtils info:IMLogTagAPI format:@"✅ 登录成功: %@", response.message];
        
        // 构建用户信息字典
        NSDictionary *userInfo = @{
            @"userId": response.data.uuid ?: @"",
            @"regTs": response.data.reg_ts ?: @"",
            @"message": response.message ?: @"",
            @"timestamp": @([[NSDate date] timeIntervalSince1970])
        };
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(YES, userInfo, nil);
            });
        }
    } failure:^(NSError *error) {
        [IMLogUtils error:IMLogTagAPI format:@"❌ 登录失败: %@", error.localizedDescription];
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
        }
    }];
}

#pragma mark - 广告策略接口

- (void)getAdStrategyWithAppId:(NSString *)appId
                          uuid:(NSString * _Nullable)uuid
                    completion:(void(^)(BOOL success, id _Nullable response, NSError * _Nullable error))completion {
    
    [IMLogUtils info:IMLogTagAPI format:@"📊 开始获取广告策略"];
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:2001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取广告策略失败: AppId为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    // 如果没有传入uuid，则使用登录后保存的uuid
    NSString *finalUuid = uuid;
    if (!finalUuid || finalUuid.length == 0) {
        finalUuid = [[IMAPIManager sharedManager] getCurrentUserUUID];
        [IMLogUtils info:IMLogTagAPI format:@"使用登录保存的UUID: %@", finalUuid ?: @"无"];
    }
    
    if (!finalUuid || finalUuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:2002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"UUID不能为空，请先登录或传入有效的UUID"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取广告策略失败: UUID为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    // 调用广告策略服务
    [[IMAdStrategyService sharedService] getAdStrategyWithAppId:appId
                                                           uuid:finalUuid
                                                        success:^(IMAdStrategyResponse *response) {
        [IMLogUtils info:IMLogTagAPI format:@"✅ 获取广告策略成功: %@", response.message];
        [Adjust addGlobalCallbackParameter:[IMAdStrategyManager sharedManager].getSDKStartupConfig.sdk_config_sdk_type forKey:@"ad_sdk"];

        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(YES, response, nil);
            });
        }
    } failure:^(NSError *error) {
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取广告策略失败: %@", error.localizedDescription];
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
        }
    }];
}

#pragma mark - 产品策略接口

- (void)getGameStrategyWithAppId:(NSString *)appId
                            uuid:(NSString * _Nullable)uuid
                      completion:(void(^)(BOOL success, NSArray * _Nullable strategyData, NSError * _Nullable error))completion {
    
    [IMLogUtils info:IMLogTagAPI format:@"📊 开始获取产品策略"];
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:3001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取产品策略失败: AppId为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    // 如果没有传入uuid，则使用登录后保存的uuid
    NSString *finalUuid = uuid;
    if (!finalUuid || finalUuid.length == 0) {
        finalUuid = [[IMAPIManager sharedManager] getCurrentUserUUID];
        [IMLogUtils info:IMLogTagAPI format:@"使用登录保存的UUID: %@", finalUuid ?: @"无"];
    }
    
    if (!finalUuid || finalUuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                             code:3002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"UUID不能为空，请先登录或传入有效的UUID"}];
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取产品策略失败: UUID为空"];
        if (completion) completion(NO, nil, error);
        return;
    }
    
    // 调用产品策略服务
    [[IMGameStrategyService sharedService] getGameStrategyWithAppId:appId
                                                               uuid:finalUuid
                                                            success:^(IMGameStrategyResponse *response) {
        [IMLogUtils info:IMLogTagAPI format:@"✅ 获取产品策略成功: %@", response.message];
        
        // 转换为简化的数据格式
        NSMutableArray *strategyArray = [NSMutableArray array];
        for (IMGameSceneStrategy *sceneData in response.data) {
            NSMutableDictionary *sceneDict = [NSMutableDictionary dictionary];
            sceneDict[@"sceneName"] = sceneData.scene_name ?: @"";
            sceneDict[@"sceneDesc"] = sceneData.scene_desc ?: @"";
            sceneDict[@"country"] = sceneData.country ?: @[];
            sceneDict[@"userType"] = @(sceneData.user_type);
            sceneDict[@"channels"] = sceneData.channels ?: @[];
            
            NSMutableArray *strategies = [NSMutableArray array];
            for (IMGameStrategy *strategy in sceneData.strategy) {
                NSMutableDictionary *strategyDict = [NSMutableDictionary dictionary];
                strategyDict[@"strategyId"] = strategy.strategy_id;
                strategyDict[@"rate"] = @(strategy.rate);
                
                if (strategy.conditions) {
                    NSMutableDictionary *conditionsDict = [NSMutableDictionary dictionary];
                    if (strategy.conditions.cur_level) {
                        conditionsDict[@"curLevel"] = strategy.conditions.cur_level;
                    }
                    if (strategy.conditions.level_interval) {
                        conditionsDict[@"levelInterval"] = strategy.conditions.level_interval;
                    }
                    if (strategy.conditions.ad_mob_first) {
                        conditionsDict[@"adMobFirst"] = strategy.conditions.ad_mob_first;
                    }
                    if (strategy.conditions.additionalConditions) {
                        [conditionsDict addEntriesFromDictionary:strategy.conditions.additionalConditions];
                    }
                    strategyDict[@"conditions"] = conditionsDict;
                }
                
                if (strategy.actions) {
                    NSMutableDictionary *actionsDict = [NSMutableDictionary dictionary];
                    if (strategy.actions.level_combine) {
                        actionsDict[@"levelCombine"] = strategy.actions.level_combine;
                    }
                    if (strategy.actions.additionalActions) {
                        [actionsDict addEntriesFromDictionary:strategy.actions.additionalActions];
                    }
                    strategyDict[@"actions"] = actionsDict;
                }
                
                [strategies addObject:strategyDict];
            }
            
            sceneDict[@"strategies"] = strategies;
            [strategyArray addObject:sceneDict];
        }
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(YES, [strategyArray copy], nil);
            });
        }
    } failure:^(NSError *error) {
        [IMLogUtils error:IMLogTagAPI format:@"❌ 获取产品策略失败: %@", error.localizedDescription];
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
        }
    }];
}

#pragma mark - FCM令牌上传接口

- (void)uploadFCMTokenWithAppId:(NSString *)appId
                           uuid:(NSString * _Nullable)uuid
                       fcmToken:(NSString *)fcmToken
                     completion:(void(^)(BOOL success, NSString * _Nullable message, NSError * _Nullable error))completion {
    
    [IMLogUtils info:IMLogTagAPI format:@"🔔 开始上传FCM令牌"];
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                              code:4001 
                                          userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
         [IMLogUtils error:IMLogTagAPI format:@"❌ 上传FCM令牌失败: AppId为空"];
         if (completion) completion(NO, nil, error);
        return;
    }
    
    // 如果没有传入uuid，则使用登录后保存的uuid
    NSString *finalUuid = uuid;
    if (!finalUuid || finalUuid.length == 0) {
        finalUuid = [[IMAPIManager sharedManager] getCurrentUserUUID];
        [IMLogUtils info:IMLogTagAPI format:@"使用登录保存的UUID: %@", finalUuid ?: @"无"];
    }
    
    if (!finalUuid || finalUuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                              code:4002 
                                          userInfo:@{NSLocalizedDescriptionKey: @"UUID不能为空，请先登录或传入有效的UUID"}];
         [IMLogUtils error:IMLogTagAPI format:@"❌ 上传FCM令牌失败: UUID为空"];
         if (completion) completion(NO, nil, error);
        return;
    }
    
    if (!fcmToken || fcmToken.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" 
                                              code:4003 
                                          userInfo:@{NSLocalizedDescriptionKey: @"FCM令牌不能为空"}];
         [IMLogUtils error:IMLogTagAPI format:@"❌ 上传FCM令牌失败: FCM令牌为空"];
         if (completion) completion(NO, nil, error);
        return;
    }
    
    // 调用FCM服务
    [[IMFCMService sharedService] uploadFCMTokenWithAppId:appId
                                                     uuid:finalUuid
                                                 fcmToken:fcmToken
                                                  success:^(IMFCMResponse *response) {
        [IMLogUtils info:IMLogTagAPI format:@"✅ FCM令牌上传成功: %@", response.message];
        
        if (completion) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 completion(YES, response.message, nil);
             });
         }
     } failure:^(NSError *error) {
         [IMLogUtils error:IMLogTagAPI format:@"❌ FCM令牌上传失败: %@", error.localizedDescription];
         
         if (completion) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 completion(NO, nil, error);
             });
         }
    }];
}

#pragma mark - 广告接口实现

// MARK: - 激励视频广告

- (void)showRewardedVideo:(NSString *)placementId viewController:(UIViewController *)viewController {
    [IMLogUtils info:IMLogTagAd format:@"🎬 展示激励视频广告: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 激励视频广告展示失败: placementId为空"];
        return;
    }
    
    if (!viewController) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 激励视频广告展示失败: viewController为空"];
        return;
    }
    
    // 获取SDK配置类型 - 添加详细调试信息
    [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] 开始获取SDK配置类型..."];
    
    // 检查策略管理器状态
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] 策略管理器实例: %@", strategyManager ? @"存在" : @"不存在"];
    
    IMSDKStartupConfig *config = [strategyManager getSDKStartupConfig];
    [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] SDK配置对象: %@", config ? @"存在" : @"不存在"];
    
    if (config) {
        [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] 配置对象详情: %@", config];
        [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] sdk_config_sdk_type原始值: %@", config.sdk_config_sdk_type];
    }
    
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 激励视频广告展示失败: sdk_config_sdk_type配置为空"];
        [IMLogUtils error:IMLogTagAd format:@"🔍 [激励视频] 配置为空的详细信息 - config存在: %@, sdkType: %@", config ? @"是" : @"否", sdkType ?: @"nil"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    [IMLogUtils info:IMLogTagAd format:@"🔍 [激励视频] SDK类型获取成功，准备根据类型调用对应广告管理器"];    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource激励视频管理器
        DMRewardedVideoManager *rewardedVideoManager = [DMRewardedVideoManager shareRewardedVideoManager];
        [rewardedVideoManager showIrSourceRV];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource激励视频广告展示"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX激励视频管理器
        DualMediationMAXRewardedVideoManager *maxRewardedVideoManager = [DualMediationMAXRewardedVideoManager sharedRewardedVideoManager];
        [maxRewardedVideoManager showRewardedVideo];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX激励视频广告展示"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 激励视频广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isRewardedVideoReady:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"🎬 检查激励视频广告状态: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查激励视频广告状态失败: placementId为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查激励视频广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource激励视频管理器
        DMRewardedVideoManager *rewardedVideoManager = [DMRewardedVideoManager shareRewardedVideoManager];
        isReady = NO; // 目前IronSource激励视频管理器暂无状态检查方法，默认返回NO
        [IMLogUtils info:IMLogTagAd format:@"📋 IronSource激励视频广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX激励视频管理器
        DualMediationMAXRewardedVideoManager *maxRewardedVideoManager = [DualMediationMAXRewardedVideoManager sharedRewardedVideoManager];
        isReady = maxRewardedVideoManager.isLoadRewardedVideo;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX激励视频广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查激励视频广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

/**
 * 显示指定场景的激励视频广告
 * @param scene 场景标识符，用于区分不同的广告展示场景
 */
+ (void)showRewardedVideoForScene:(NSString *)scene {
    [IMLogUtils info:IMLogTagAd format:@"🎬 [场景化] 展示激励视频广告，场景: %@", scene];
    
    if (!scene || scene.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 激励视频广告展示失败: 场景标识符为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 激励视频广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 [场景化] 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource激励视频管理器
        DMRewardedVideoManager *rewardedVideoManager = [DMRewardedVideoManager shareRewardedVideoManager];
        [rewardedVideoManager showIrSourceRVForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ [场景化] 调用IronSource激励视频广告展示，场景: %@", scene];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX激励视频管理器
        DualMediationMAXRewardedVideoManager *maxRewardedVideoManager = [DualMediationMAXRewardedVideoManager sharedRewardedVideoManager];
        [maxRewardedVideoManager showRewardedVideoForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ [场景化] 调用MAX激励视频广告展示，场景: %@", scene];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 激励视频广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

/**
 * 检查指定场景的激励视频广告是否准备就绪
 * @param scene 场景标识符
 * @return YES表示广告已准备就绪，NO表示广告未准备就绪
 */
+ (BOOL)isRewardedVideoReadyForScene:(NSString *)scene {
    [IMLogUtils info:IMLogTagAd format:@"🎬 [场景化] 检查激励视频广告状态，场景: %@", scene];
    
    if (!scene || scene.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 检查激励视频广告状态失败: 场景标识符为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 检查激励视频广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource激励视频管理器检查状态
        DMRewardedVideoManager *rewardedVideoManager = [DMRewardedVideoManager shareRewardedVideoManager];
        isReady = [rewardedVideoManager isRewardedVideoReadyForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"📋 [场景化] IronSource激励视频广告状态: %@，场景: %@", isReady ? @"已准备" : @"未准备", scene];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX激励视频管理器检查状态
        DualMediationMAXRewardedVideoManager *maxRewardedVideoManager = [DualMediationMAXRewardedVideoManager sharedRewardedVideoManager];
        isReady = [maxRewardedVideoManager isRewardedVideoReadyForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"📋 [场景化] MAX激励视频广告状态: %@，场景: %@", isReady ? @"已准备" : @"未准备", scene];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ [场景化] 检查激励视频广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

// MARK: - 插屏广告

- (void)showInterstitial:(NSString *)placementId viewController:(UIViewController *)viewController {
    [IMLogUtils info:IMLogTagAd format:@"📱 展示插屏广告: %@", placementId];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeInsert]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 插屏广告已被禁用，跳过展示: %@", placementId];
        return;
    }
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: placementId为空"];
        return;
    }
    
    if (!viewController) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: viewController为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource插屏广告管理器
        DMInterstitialManager *interstitialManager = [DMInterstitialManager shareInterstitialManager];
        [interstitialManager showInterstitial];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource插屏广告展示"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX插屏广告管理器
        DualMediationMAXInterstitialManager *maxInterstitialManager = [DualMediationMAXInterstitialManager sharedInterstitialManager];
        [maxInterstitialManager showInterstitial];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX插屏广告展示"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isInterstitialReady:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"📱 检查插屏广告状态: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: placementId为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource插屏广告管理器检查状态
        DMInterstitialManager *interstitialManager = [DMInterstitialManager shareInterstitialManager];
        // IronSource插屏广告管理器暂无状态检查方法，默认返回NO
        isReady = NO;
        [IMLogUtils info:IMLogTagAd format:@"📋 IronSource插屏广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX插屏广告管理器检查状态
        DualMediationMAXInterstitialManager *maxInterstitialManager = [DualMediationMAXInterstitialManager sharedInterstitialManager];
        isReady = maxInterstitialManager.isLoadInterstitial;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX插屏广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

// MARK: - 开屏广告

- (void)showSplash:(NSString *)placementId viewController:(UIViewController *)viewController {
    [IMLogUtils info:IMLogTagAd format:@"🚀 展示开屏广告: %@", placementId];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeSplash]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 开屏广告已被禁用，跳过展示: %@", placementId];
        return;
    }
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 开屏广告展示失败: placementId为空"];
        return;
    }
    
    if (!viewController) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 开屏广告展示失败: viewController为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 开屏广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"]  || [sdkType isEqualToString:@"IS&MAX"]) {
        // IronSource暂不支持开屏广告
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ IronSource暂不支持开屏广告，placementId: %@", placementId];
        return;
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // MAX开屏广告展示（内部实现）
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX开屏广告展示"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 开屏广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isSplashReady:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"🚀 检查开屏广告状态: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查开屏广告状态失败: placementId为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查开屏广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // IronSource暂不支持开屏广告
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ IronSource暂不支持开屏广告，placementId: %@", placementId];
        isReady = NO;
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // MAX开屏广告状态检查（内部实现）
        isReady = NO;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX开屏广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查开屏广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

- (void)setSplashAdDisable:(BOOL)isDisable {
    [IMLogUtils info:IMLogTagAd format:@"🚀 设置开屏广告禁用状态: %@", isDisable ? @"禁用" : @"启用"];
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 设置开屏广告禁用状态失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // IronSource暂不支持开屏广告
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ IronSource暂不支持开屏广告设置"];
        return;
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // MAX开屏广告禁用状态设置（内部实现）
        [IMLogUtils info:IMLogTagAd format:@"✅ MAX开屏广告禁用状态设置完成"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 设置开屏广告禁用状态失败: 不支持的SDK类型 %@", sdkType];
    }
}

// MARK: - Banner广告

- (void)showBanner:(NSString *)placementId 
     containerView:(UIView *)containerView 
          position:(nullable NSValue *)position {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner广告: %@", placementId];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeBanner]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 Banner广告已被禁用，跳过展示: %@", placementId];
        return;
    }
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: placementId为空"];
        return;
    }
    
    if (!containerView) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: containerView为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        [bannerManager showBanner];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告展示"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager showBanner];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告展示"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isBannerReady:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 检查Banner广告状态: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: placementId为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"]  || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器检查状态
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        // IronSource Banner广告管理器暂无状态检查方法，默认返回NO
        isReady = NO;
        [IMLogUtils info:IMLogTagAd format:@"📋 IronSource Banner广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器检查状态
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        isReady = maxBannerManager.isLoadBanner;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX Banner广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

- (void)hideBanner:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 隐藏Banner广告: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: placementId为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        [bannerManager hideBanner];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告隐藏"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager hideBanner];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告隐藏"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: 不支持的SDK类型 %@", sdkType];
    }
}

// MARK: - 原生广告

- (void)showNativeAd:(NSString *)placementId 
        containerView:(UIView *)containerView 
               adView:(nullable UIView *)adView {
    [IMLogUtils info:IMLogTagAd format:@"📰 展示原生广告: %@", placementId];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeNative]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 原生广告已被禁用，跳过展示: %@", placementId];
        return;
    }
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: placementId为空"];
        return;
    }
    
    if (!containerView) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: containerView为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource原生广告管理器
        DMNativeAdManager *nativeAdManager = [DMNativeAdManager sharedInstance];
        // IronSource原生广告管理器不提供直接显示方法，通过loadNativeAd和renderAdToContainer实现
        [nativeAdManager loadNativeAd];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource原生广告展示"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX原生广告管理器
        DualMediationMAXNativeADManager *maxNativeAdManager = [DualMediationMAXNativeADManager sharedNativeADManager];
        // MAX原生广告管理器不提供直接显示方法，通过loadNativeAd和renderAdToContainer实现
        [maxNativeAdManager loadNativeAd];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX原生广告展示"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isNativeAdReady:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"📰 检查原生广告状态: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查原生广告状态失败: placementId为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查原生广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource原生广告管理器检查状态
        DMNativeAdManager *nativeAdManager = [DMNativeAdManager sharedInstance];
        // IronSource原生广告管理器暂无状态检查方法，默认返回NO
        isReady = NO;
        [IMLogUtils info:IMLogTagAd format:@"📋 IronSource原生广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX原生广告管理器检查状态
        DualMediationMAXNativeADManager *maxNativeAdManager = [DualMediationMAXNativeADManager sharedNativeADManager];
        isReady = maxNativeAdManager.isLoadNativeAd;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX原生广告状态: %@", isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查原生广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

- (nullable NSDictionary *)getNativeAdData:(NSString *)placementId {
    [IMLogUtils info:IMLogTagAd format:@"📰 获取原生广告数据: %@", placementId];
    
    if (!placementId || placementId.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 获取原生广告数据失败: placementId为空"];
        return nil;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 获取原生广告数据失败: sdk_config_sdk_type配置为空"];
        return nil;
    }
    
    NSDictionary *adData = nil;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource原生广告管理器获取数据
        DMNativeAdManager *nativeAdManager = [DMNativeAdManager sharedInstance];
        // IronSource原生广告管理器暂无数据获取方法，返回nil
        adData = nil;
        [IMLogUtils info:IMLogTagAd format:@"📋 获取IronSource原生广告数据: %@", adData ? @"成功" : @"失败"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX原生广告管理器获取数据
        DualMediationMAXNativeADManager *maxNativeAdManager = [DualMediationMAXNativeADManager sharedNativeADManager];
        // MAX原生广告管理器暂无数据获取方法，返回nil
        adData = nil;
        [IMLogUtils info:IMLogTagAd format:@"📋 获取MAX原生广告数据: %@", adData ? @"成功" : @"失败"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 获取原生广告数据失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return adData;
}

#pragma mark - 原生广告场景化接口实现

- (void)showNative:(NSString *)sceneValue position:(DMNativePosition)position {
    [IMLogUtils info:IMLogTagAd format:@"📰 展示原生广告 - 场景: %@, 位置: %@", sceneValue, position == DMNativePositionTop ? @"顶部" : @"底部"];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeNative]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 原生广告已被禁用，跳过展示 - 场景: %@", sceneValue];
        return;
    }
    
    if (!sceneValue || sceneValue.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: 场景值为空"];
        if (self.adDelegate && [self.adDelegate respondsToSelector:@selector(onNativeShowFail:position:error:)]) {
            NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" code:2001 userInfo:@{NSLocalizedDescriptionKey: @"场景值不能为空"}];
            [self.adDelegate onNativeShowFail:sceneValue position:position error:error];
        }
        return;
    }
    
    // 获取原生广告策略配置
    DMNativeStrategyParser *strategyParser = [DMNativeStrategyParser sharedParser];
    
    // 检查场景是否启用原生广告
    if (![strategyParser isNativeEnabledForScene:sceneValue]) {
        [IMLogUtils info:IMLogTagAd format:@"📋 场景 %@ 原生广告未启用，跳过展示", sceneValue];
        return;
    }
    
    // 获取策略配置的位置（如果策略有配置，优先使用策略配置）
    NSString *strategyPosition = [strategyParser getNativePositionForScene:sceneValue];
    DMNativePosition finalPosition = position; // 默认使用传入的位置
    
    if (strategyPosition && strategyPosition.length > 0) {
        if ([strategyPosition isEqualToString:@"top"]) {
            finalPosition = DMNativePositionTop;
        } else if ([strategyPosition isEqualToString:@"bottom"]) {
            finalPosition = DMNativePositionBottom;
        }
        [IMLogUtils info:IMLogTagAd format:@"📋 使用策略配置位置: %@", strategyPosition];
    }
    
    // 获取等待时间
    NSInteger waitTime = [strategyParser getNativeWaitTimeForScene:sceneValue];
    if (waitTime > 0) {
        [IMLogUtils info:IMLogTagAd format:@"⏰ 场景 %@ 需要等待 %ld 秒后显示原生广告", sceneValue, (long)waitTime];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self performNativeAdShowWithScene:sceneValue position:finalPosition];
        });
        return;
    }
    
    // 立即显示
    [self performNativeAdShowWithScene:sceneValue position:finalPosition];
}

/**
 * 执行原生广告显示的具体逻辑
 * @param sceneValue 场景值
 * @param position 显示位置
 */
- (void)performNativeAdShowWithScene:(NSString *)sceneValue position:(DMNativePosition)position {
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: sdk_config_sdk_type配置为空 - 场景: %@", sceneValue];
        if (self.adDelegate && [self.adDelegate respondsToSelector:@selector(onNativeShowFail:position:error:)]) {
            NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" code:2002 userInfo:@{NSLocalizedDescriptionKey: @"SDK类型配置为空"}];
            [self.adDelegate onNativeShowFail:sceneValue position:position error:error];
        }
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@ - 场景: %@", sdkType, sceneValue];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource原生广告管理器
        DMNativeAdManager *nativeAdManager = [DMNativeAdManager sharedInstance];
        // 设置代理和场景
        [nativeAdManager setDelegate:self];
        [nativeAdManager setCurrentScene:sceneValue];
        
        // 先加载广告
        [nativeAdManager loadNativeAd];
        
        // 创建容器视图并渲染广告
        UIView *containerView = [self createNativeContainerViewForPosition:position];
        if (containerView) {
            [nativeAdManager renderAdToContainer:containerView];
        }
        
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource原生广告展示 - 场景: %@", sceneValue];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX原生广告管理器
        DualMediationMAXNativeADManager *maxNativeAdManager = [DualMediationMAXNativeADManager sharedNativeADManager];
        // 设置代理和场景
        [maxNativeAdManager setDelegate:self];
        [maxNativeAdManager setCurrentScene:sceneValue];
        
        // 先加载广告
        [maxNativeAdManager loadNativeAd];
        
        // 创建容器视图并渲染广告
        UIView *containerView = [self createNativeContainerViewForPosition:position];
        if (containerView) {
            [maxNativeAdManager renderAdToContainer:containerView];
        }
        
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX原生广告展示 - 场景: %@", sceneValue];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告展示失败: 不支持的SDK类型 %@ - 场景: %@", sdkType, sceneValue];
        if (self.adDelegate && [self.adDelegate respondsToSelector:@selector(onNativeShowFail:position:error:)]) {
            NSError *error = [NSError errorWithDomain:@"DualMediationSDKPublic" code:2003 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"不支持的SDK类型: %@", sdkType]}];
            [self.adDelegate onNativeShowFail:sceneValue position:position error:error];
        }
    }
}

// 创建原生广告容器视图
- (UIView *)createNativeContainerViewForPosition:(DMNativePosition)position {
    [IMLogUtils info:IMLogTagAd format:@"📰 创建原生广告容器视图 - 位置: %@", position == DMNativePositionTop ? @"顶部" : @"底部"];
    
    // 获取主窗口
    UIWindow *keyWindow = nil;
    for (UIWindow *w in [UIApplication sharedApplication].windows) {
        if (w.isKeyWindow) { keyWindow = w; break; }
    }
    if (!keyWindow) keyWindow = [UIApplication sharedApplication].delegate.window;
    
    // 获取顶层视图控制器
    UIViewController *topVC = [self topMostViewController];
    if (!topVC) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 无法获取顶层视图控制器，无法创建容器视图"];
        return nil;
    }
    
    // 创建容器视图
    UIView *containerView = [[UIView alloc] init];
    containerView.translatesAutoresizingMaskIntoConstraints = NO;
    containerView.backgroundColor = [UIColor clearColor];
    containerView.clipsToBounds = YES;
    containerView.layer.cornerRadius = 8.0;
    
    // 添加到顶层视图
    [topVC.view addSubview:containerView];
    
    // 设置约束
    CGFloat containerHeight = 250.0; // 原生广告高度
    CGFloat horizontalMargin = 16.0; // 水平边距
    
    if (position == DMNativePositionTop) {
        // 顶部位置
        [NSLayoutConstraint activateConstraints:@[
            [containerView.topAnchor constraintEqualToAnchor:topVC.view.safeAreaLayoutGuide.topAnchor constant:horizontalMargin],
            [containerView.leadingAnchor constraintEqualToAnchor:topVC.view.leadingAnchor constant:horizontalMargin],
            [containerView.trailingAnchor constraintEqualToAnchor:topVC.view.trailingAnchor constant:-horizontalMargin],
            [containerView.heightAnchor constraintEqualToConstant:containerHeight]
        ]];
    } else {
        // 底部位置
        [NSLayoutConstraint activateConstraints:@[
            [containerView.bottomAnchor constraintEqualToAnchor:topVC.view.safeAreaLayoutGuide.bottomAnchor constant:-horizontalMargin],
            [containerView.leadingAnchor constraintEqualToAnchor:topVC.view.leadingAnchor constant:horizontalMargin],
            [containerView.trailingAnchor constraintEqualToAnchor:topVC.view.trailingAnchor constant:-horizontalMargin],
            [containerView.heightAnchor constraintEqualToConstant:containerHeight]
        ]];
    }
    
    return containerView;
}

- (UIViewController *)topMostViewController {
    UIWindow *keyWindow = nil;
    for (UIWindow *w in [UIApplication sharedApplication].windows) {
        if (w.isKeyWindow) { keyWindow = w; break; }
    }
    if (!keyWindow) keyWindow = [UIApplication sharedApplication].delegate.window;
    return [self _topFrom: keyWindow.rootViewController];
}

- (UIViewController *)_topFrom:(UIViewController *)vc {
    if (vc.presentedViewController) {
        return [self _topFrom:vc.presentedViewController];
    } else if ([vc isKindOfClass:UINavigationController.class]) {
        return [self _topFrom:((UINavigationController*)vc).visibleViewController];
    } else if ([vc isKindOfClass:UITabBarController.class]) {
        return [self _topFrom:((UITabBarController*)vc).selectedViewController];
    }
    return vc;
}

- (void)hideNative:(NSString *)sceneValue {
    [IMLogUtils info:IMLogTagAd format:@"📰 隐藏原生广告 - 场景: %@", sceneValue];
    
    if (!sceneValue || sceneValue.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告隐藏失败: 场景值为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告隐藏失败: sdk_config_sdk_type配置为空 - 场景: %@", sceneValue];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@ - 场景: %@", sdkType, sceneValue];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource原生广告管理器
        DMNativeAdManager *nativeAdManager = [DMNativeAdManager sharedInstance];
        // 调用内部销毁方法
        [nativeAdManager destroyNativeAd];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource原生广告销毁 - 场景: %@", sceneValue];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX原生广告管理器
        DualMediationMAXNativeADManager *maxNativeAdManager = [DualMediationMAXNativeADManager sharedNativeADManager];
        // 调用内部销毁方法
        [maxNativeAdManager destroyNativeAd];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX原生广告销毁 - 场景: %@", sceneValue];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 原生广告隐藏失败: 不支持的SDK类型 %@ - 场景: %@", sdkType, sceneValue];
    }
    
    // 触发新的移除回调
    if (self.adDelegate && [self.adDelegate respondsToSelector:@selector(onNativeRemoved:)]) {
        [self.adDelegate onNativeRemoved:sceneValue];
    }
}

#pragma mark - 便捷方法

+ (void)IninSDK {
    [[DualMediationSDKPublic sharedInstance] initializeSDKWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ DualMediationSDK 快速启动成功，开始执行自动登录流程"];
            // SDK初始化成功后，自动执行登录和策略接口调用流程
            [[DualMediationSDKPublic sharedInstance] executeAutoLoginAndStrategyFlow];
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ DualMediationSDK 快速启动失败: %@", error.localizedDescription];
        }
    }];
}

+ (void)IninSDKWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [[DualMediationSDKPublic sharedInstance] initializeSDKWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ DualMediationSDK 快速启动成功，开始执行自动登录流程"];
            // SDK初始化成功后，自动执行登录和策略接口调用流程
            [[DualMediationSDKPublic sharedInstance] executeAutoLoginAndStrategyFlow];
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ DualMediationSDK 快速启动失败: %@", error.localizedDescription];
        }
        
        // 执行回调
        if (completion) {
            completion(success, error);
        }
    }];
}

+ (void)enableDebugMode {
    [[DualMediationSDKPublic sharedInstance] setDebugModeEnabled:YES];
}

+ (DMLifecycleManager *)lifecycleManager {
    return [DMLifecycleManager sharedManager];
}

#pragma mark - 设备信息接口实现

- (NSDictionary *)getDeviceInfo {
    [IMLogUtils info:IMLogTagAPI format:@"📱 获取设备基本信息"];
    return [[IMDeviceInfoService sharedService] getDeviceInfo];
}

- (NSDictionary *)getDetailedDeviceInfo {
    [IMLogUtils info:IMLogTagAPI format:@"📱 获取设备详细信息"];
    return [[IMDeviceInfoService sharedService] getDetailedDeviceInfo];
}

- (NSDictionary *)getNetworkInfo {
    [IMLogUtils info:IMLogTagAPI format:@"🌐 获取设备网络信息"];
    return [[IMDeviceInfoService sharedService] getNetworkInfo];
}

#pragma mark - FCM推送接口实现

- (void)handleRemoteNotification:(NSDictionary *)userInfo 
                completionHandler:(nullable void (^)(NSInteger))completionHandler {
    [IMLogUtils info:IMLogTagAPI format:@"🔔 处理远程通知"];
    
    // 调用IMFCMPushService处理远程通知
//    [[IMFCMPushService sharedService] handleRemoteNotification:userInfo 
//                                             completionHandler:^(UIBackgroundFetchResult result) {
//        if (completionHandler) {
//            completionHandler((NSInteger)result);
//        }
//    }];
}

- (void)handleNotificationTap:(NSDictionary *)userInfo 
               viewController:(UIViewController *)viewController {
    [IMLogUtils info:IMLogTagAPI format:@"🔔 处理通知点击事件"];
    [[IMFCMPushService sharedService] handleNotificationTap:userInfo 
                                             viewController:viewController];
}

- (BOOL)isFCMNotification:(NSDictionary *)userInfo {
    return [[IMFCMPushService sharedService] isFCMNotification:userInfo];
}

#pragma mark - 震动功能接口实现

- (void)vibrateWithDuration:(NSTimeInterval)duration {
    [IMLogUtils info:IMLogTagAPI format:@"📳 执行简单震动，时长: %.1f秒", duration];
    [[IMVibrateService sharedService] vibrateWithDuration:duration completion:nil];
}

- (void)vibrateWithPattern:(NSArray<NSNumber *> *)pattern {
    [IMLogUtils info:IMLogTagAPI format:@"📳 执行模式震动，模式: %@", pattern];
    [[IMVibrateService sharedService] vibrateWithPattern:pattern repeatCount:1 completion:nil];
}

- (void)vibrateWithType:(NSInteger)type {
    [IMLogUtils info:IMLogTagAPI format:@"📳 执行类型震动，类型: %ld", (long)type];
    [[IMVibrateService sharedService] vibrateWithType:(IMVibrateType)type intensity:IMVibrateIntensityMedium completion:nil];
}

- (NSString *)vibrateWithConfig:(NSDictionary *)config 
                progressCallback:(nullable void (^)(NSString *vibrateId, float progress))progressCallback {
    [IMLogUtils info:IMLogTagAPI format:@"📳 执行高级震动配置: %@", config];
    
    // 将字典转换为IMVibrateConfig对象
    IMVibrateConfig *vibrateConfig = [self convertDictionaryToVibrateConfig:config];
    if (!vibrateConfig) {
        [IMLogUtils error:IMLogTagAPI format:@"❌ 震动配置转换失败"];
        return nil;
    }
    
    // 转换进度回调
    IMVibrateProgressBlock convertedProgressCallback = nil;
    if (progressCallback) {
        convertedProgressCallback = ^(NSString *vibrateId, NSInteger currentCount) {
            float progress = (float)currentCount;
            progressCallback(vibrateId, progress);
        };
    }
    
    IMVibrateResult *result = [[IMVibrateService sharedService] vibrateWithConfig:vibrateConfig 
                                                                         progress:convertedProgressCallback
                                                                       completion:nil];
    return result.vibrateId;
}

- (void)cancelVibrate:(NSString *)vibrateId {
    [IMLogUtils info:IMLogTagAPI format:@"📳 取消震动: %@", vibrateId];
    [[IMVibrateService sharedService] cancelVibrateWithId:vibrateId];
}

- (void)pauseVibrate:(NSString *)vibrateId {
    [IMLogUtils info:IMLogTagAPI format:@"📳 暂停震动: %@", vibrateId];
    [[IMVibrateService sharedService] pauseVibrateWithId:vibrateId];
}

- (void)resumeVibrate:(NSString *)vibrateId {
    [IMLogUtils info:IMLogTagAPI format:@"📳 恢复震动: %@", vibrateId];
    [[IMVibrateService sharedService] resumeVibrateWithId:vibrateId];
}

- (BOOL)isVibrateSupported {
    return [[IMVibrateService sharedService] isVibrateSupported];
}

- (BOOL)isHapticFeedbackSupported {
    return [[IMVibrateService sharedService] isHapticFeedbackSupported];
}

- (NSInteger)getActiveVibrateCount {
    return [[IMVibrateService sharedService] activeVibrationsCount];
}

#pragma mark - SDK启动配置接口

/**
 * 手动应用SDK启动配置
 * 从广告策略中获取并应用SDK启动配置参数
 */
- (void)applySDKStartupConfiguration {
    [IMLogUtils info:IMLogTagAPI format:@"🔧 手动触发SDK启动配置应用"];
    
    if (!self.isSDKInitialized) {
        [IMLogUtils warning:IMLogTagAPI format:@"⚠️ SDK尚未初始化，无法应用启动配置"];
        return;
    }
    
    [self applySDKStartupConfigurationFromAdStrategy];
}

/**
 * 应用默认SDK启动配置
 */
- (void)applyDefaultSDKStartupConfiguration {
    [IMLogUtils info:IMLogTagAPI format:@"🔧 应用默认SDK启动配置"];
    [[IMSDKStartupConfigManager sharedManager] applyDefaultSDKStartupConfig];
}

#pragma mark - 私有辅助方法

/**
 * 执行自动登录和策略接口调用流程
 * 登录失败时会重试最多5次，登录成功后调用产品策略和广告策略接口
 */
- (void)executeAutoLoginAndStrategyFlow {
    [IMLogUtils info:IMLogTagSDKInit format:@"🚀 开始执行自动登录和策略接口调用流程"];
    
    // 从IMAPIManager获取已保存的UUID
    NSString *savedUUID = [[IMAPIManager sharedManager] getCurrentUserUUID];
    if (!savedUUID || savedUUID.length == 0) {
        [IMLogUtils info:IMLogTagSDKInit format:@"📱 首次使用：未找到已保存的UUID，正在生成新的UUID..."];
        
        // 首次使用，从钥匙串获取或创建新的UUID
        savedUUID = [IMKeychainUUIDManager getOrCreateLoginUUID];
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 已生成新的UUID并保存到钥匙串: %@", savedUUID];
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 使用UUID执行自动登录: %@", savedUUID];
    
    // 开始登录重试流程
    [self attemptLoginWithUUID:savedUUID retryCount:0 maxRetries:5];
}

/**
 * 尝试登录，支持重试机制
 * @param uuid 用户UUID
 * @param retryCount 当前重试次数
 * @param maxRetries 最大重试次数
 */
- (void)attemptLoginWithUUID:(NSString *)uuid retryCount:(NSInteger)retryCount maxRetries:(NSInteger)maxRetries {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔐 开始登录尝试 (第%ld次，最多%ld次)", (long)(retryCount + 1), (long)maxRetries];
    
    [[IMLoginService sharedService] loginWithAppId:[[DMConfigReader sharedInstance] sdkAppId]
                                            iosUuid:uuid
                                        countryCode:@"CN" 
                                            success:^(IMLoginResponse *response) {
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 自动登录成功！开始调用策略接口"];
        [IMLogUtils info:IMLogTagSDKInit format:@"👤 用户信息: %@", response];
        
        // 保存登录成功后返回的UUID到NSUserDefaults
        if (response.data && response.data.uuid) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:response.data.uuid forKey:@"userUUID"];
            [defaults setObject:@([[NSDate date] timeIntervalSince1970]) forKey:@"loginTimestamp"];
            [defaults synchronize];
            [IMLogUtils info:IMLogTagSDKInit format:@"💾 已保存登录返回的UUID: %@", response.data.uuid];
        }
        
        // 登录成功，调用策略接口
        [self executeStrategyAPIs];
    } failure:^(NSError *error) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ 登录失败 (第%ld次尝试): %@", (long)(retryCount + 1), error.localizedDescription];
        
        // 检查是否还有重试机会
        if (retryCount < maxRetries - 1) {
            NSInteger nextRetry = retryCount + 1;
            [IMLogUtils info:IMLogTagSDKInit format:@"🔄 准备进行第%ld次重试...", (long)(nextRetry + 1)];
            
            // 延迟1秒后重试
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self attemptLoginWithUUID:uuid retryCount:nextRetry maxRetries:maxRetries];
            });
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"💥 登录失败，已达到最大重试次数(%ld次)，继续使用设备UUID尝试策略流程", (long)maxRetries];
            
            // 持久化UUID以便策略流程使用
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            if (uuid && uuid.length > 0) {
                [defaults setObject:uuid forKey:IMLoginUserUUIDKey];
                [defaults setObject:@([[NSDate date] timeIntervalSince1970]) forKey:IMLoginTimestampKey];
            }
            // 记录最后错误
            [defaults setObject:error.localizedDescription ?: @"login_failed" forKey:IMLoginErrorKey];
            [defaults synchronize];
            
            // 继续策略接口调用
            [self executeStrategyAPIs];
        }
    }];
}

/**
 * 执行策略接口调用（产品策略和广告策略）
 */
- (void)executeStrategyAPIs {
    [IMLogUtils info:IMLogTagSDKInit format:@"📋 开始调用策略接口..."];
    
    // 获取已保存的UUID；若为空，回退到钥匙串并持久化
    NSString *savedUUID = [[IMAPIManager sharedManager] getCurrentUserUUID];
    if (!savedUUID || savedUUID.length == 0) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"⚠️ 未找到IMAPIManager的UUID，尝试使用钥匙串UUID"];
        savedUUID = [IMKeychainUUIDManager getOrCreateLoginUUID];
        if (savedUUID && savedUUID.length > 0) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:savedUUID forKey:IMLoginUserUUIDKey];
            [defaults setObject:@([[NSDate date] timeIntervalSince1970]) forKey:IMLoginTimestampKey];
            [defaults synchronize];
            [IMLogUtils info:IMLogTagSDKInit format:@"💾 已持久化钥匙串UUID供策略使用: %@", savedUUID];
        }
    }
    
    if (!savedUUID || savedUUID.length == 0) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ 策略接口调用失败：无法获取UUID"];
        return;
    }
    
    // 并行调用产品策略和广告策略接口
    dispatch_group_t group = dispatch_group_create();
    
    // 调用产品策略接口
    dispatch_group_enter(group);
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 正在获取产品策略..."];
//    [[IMGameStrategyService sharedService] getGameStrategyWithAppId:[[DMConfigReader sharedInstance] sdkAppId]
//                                                               uuid:savedUUID
//                                                            success:^(IMGameStrategyResponse *response) {
//        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 产品策略获取成功: %@", response];
//        dispatch_group_leave(group);
//    } failure:^(NSError *error) {
//        [IMLogUtils error:IMLogTagSDKInit format:@"❌ 产品策略获取失败: %@", error.localizedDescription];
//        dispatch_group_leave(group);
//    }];
    
    // 调用广告策略接口
    dispatch_group_enter(group);
    [IMLogUtils info:IMLogTagSDKInit format:@"📺 正在获取广告策略..."];
    [[IMAdStrategyService sharedService] getAdStrategyWithAppId:[[DMConfigReader sharedInstance] sdkAppId]
                                                           uuid:savedUUID 
                                                        success:^(IMAdStrategyResponse *response) {
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 广告策略获取成功: %@", response];
        
        // 更新策略数据到AdStrategyManager
        [[IMAdStrategyManager sharedManager] updateStrategiesFromResponse:response];
        
        // 自动应用SDK启动配置
        [self applySDKStartupConfigurationFromAdStrategy];
        
        dispatch_group_leave(group);
    } failure:^(NSError *error) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ 广告策略获取失败: %@", error.localizedDescription];
        
        // 广告策略获取失败时，应用默认SDK启动配置
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 广告策略获取失败，应用默认SDK启动配置"];
        [[IMSDKStartupConfigManager sharedManager] applyDefaultSDKStartupConfig];
        
        dispatch_group_leave(group);
    }];
    
    // 等待所有策略接口调用完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [IMLogUtils info:IMLogTagSDKInit format:@"🎉 自动登录和策略接口调用流程全部完成！"];
    });
}

- (IMVibrateConfig *)convertDictionaryToVibrateConfig:(NSDictionary *)dict {
    if (!dict || ![dict isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    // 获取震动类型
    NSNumber *typeNumber = dict[@"type"];
    IMVibrateType type = typeNumber ? (IMVibrateType)[typeNumber integerValue] : IMVibrateTypeLight;
    
    // 获取震动强度
    NSNumber *intensityNumber = dict[@"intensity"];
    IMVibrateIntensity intensity = intensityNumber ? (IMVibrateIntensity)[intensityNumber integerValue] : IMVibrateIntensityMedium;
    
    // 获取震动模式
    NSNumber *modeNumber = dict[@"mode"];
    IMVibrateMode mode = modeNumber ? (IMVibrateMode)[modeNumber integerValue] : IMVibrateModeOnce;
    
    // 获取时长
    NSNumber *durationNumber = dict[@"duration"];
    NSTimeInterval duration = durationNumber ? [durationNumber doubleValue] : 0.5;
    
    // 获取频率数组
    NSArray *frequencies = dict[@"frequencies"];
    
    // 获取重复次数
    NSNumber *repeatCountNumber = dict[@"repeatCount"];
    NSInteger repeatCount = repeatCountNumber ? [repeatCountNumber integerValue] : 1;
    
    // 创建配置对象
    IMVibrateConfig *config = nil;
    
    switch (mode) {
        case IMVibrateModeOnce:
            config = [IMVibrateConfig configWithType:type intensity:intensity];
            config.duration = duration;
            config.mode = IMVibrateModeOnce;
            break;
        case IMVibrateModePattern:
            if (frequencies && [frequencies isKindOfClass:[NSArray class]]) {
                config = [IMVibrateConfig configWithPattern:frequencies repeatCount:repeatCount];
                config.type = type;
                config.intensity = intensity;
            } else {
                config = [IMVibrateConfig configWithDuration:duration];
                config.type = type;
                config.intensity = intensity;
            }
            break;
        case IMVibrateModeRepeat:
            config = [IMVibrateConfig configWithType:type intensity:intensity];
            config.duration = duration;
            config.repeatCount = repeatCount;
            config.mode = IMVibrateModeRepeat;
            break;
        default:
            config = [IMVibrateConfig configWithType:type intensity:intensity];
            config.duration = duration;
            config.mode = IMVibrateModeOnce;
            break;
    }
    
    return config;
}

/**
 * 从广告策略中应用SDK启动配置
 */
- (void)applySDKStartupConfigurationFromAdStrategy {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔧 开始应用SDK启动配置..."];
    
    @try {
        // 获取SDK启动配置
        IMSDKStartupConfig *startupConfig = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
        
        if (startupConfig) {
            [IMLogUtils info:IMLogTagSDKInit format:@"📋 找到SDK启动配置，开始应用配置参数"];
            
            // 应用配置
            [[IMSDKStartupConfigManager sharedManager] applySDKStartupConfig:startupConfig];
            
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ SDK启动配置应用成功"];
            [IMLogUtils info:IMLogTagSDKInit format:@"📊 配置详情:"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 日志开关: %@", startupConfig.sdk_config_log ? @"开启" : @"关闭"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 新用户天数: %@", startupConfig.sdk_config_new_user_day ?: @"未设置"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 用户分层开关: %@", startupConfig.sdk_config_user_switch ? @"开启" : @"关闭"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 美国隐私弹窗: %@", startupConfig.sdk_config_us_privacy ? @"开启" : @"关闭"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - Adjust事件: %@", startupConfig.sdk_config_adjust_event ?: @"未设置"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - SDK类型: %@", startupConfig.sdk_config_sdk_type ?: @"未设置"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 广告行为上报: %@", startupConfig.sdk_config_ad_track ? @"开启" : @"关闭"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - 广告加载上报: %@", startupConfig.sdk_config_ad_load_track ? @"开启" : @"关闭"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - Facebook控制: %@", startupConfig.sdk_config_fb_ctl ?: @"未设置"];
            [IMLogUtils info:IMLogTagSDKInit format:@"  - Facebook关卡事件: %@", startupConfig.sdk_config_fb_level_event ?: @"未设置"];
            
            // 根据SDK类型初始化对应的广告聚合平台
            [self initializeAdPlatformWithSDKType:startupConfig.sdk_config_sdk_type];
            
        } else {
            [IMLogUtils warning:IMLogTagSDKInit format:@"⚠️ 未找到SDK启动配置，应用默认配置"];
            [[IMSDKStartupConfigManager sharedManager] applyDefaultSDKStartupConfig];
            
            // 使用默认SDK类型初始化广告平台
            [self initializeAdPlatformWithSDKType:nil];
        }
        
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ SDK启动配置应用异常: %@", exception.reason];
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 异常处理：应用默认SDK启动配置"];
        [[IMSDKStartupConfigManager sharedManager] applyDefaultSDKStartupConfig];
    }
}

/**
 * 根据SDK类型初始化对应的广告聚合平台
 * @param sdkType SDK类型字符串（"IS" 或 "MAX"）
 */
- (void)initializeAdPlatformWithSDKType:(NSString *)sdkType {
    [IMLogUtils info:IMLogTagSDKInit format:@"🚀 开始根据SDK类型初始化广告聚合平台..."];
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"⚠️ SDK类型未设置，使用默认类型 IS"];
        sdkType = @"IS";
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📋 检测到SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"]) {
        // 初始化IronSource广告聚合平台
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 正在初始化 IronSource 广告聚合平台..."];
        @try {
            [[DMIronsourceManager shareIronSourceManager] initIronSource];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ IronSource 广告聚合平台初始化成功"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ IronSource 广告聚合平台初始化失败: %@", exception.reason];
        }
        
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 初始化MAX广告聚合平台
        [IMLogUtils info:IMLogTagSDKInit format:@"🔧 正在初始化 MAX 广告聚合平台..."];
        @try {
            [[DualMediationMAXManager sharedMAXManager] initMAX];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ MAX 广告聚合平台初始化成功"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ MAX 广告聚合平台初始化失败: %@", exception.reason];
        }
        
    } else {
        [IMLogUtils warning:IMLogTagSDKInit format:@"⚠️ 未知的SDK类型: %@，默认使用 IronSource", sdkType];
        @try {
            [[DMIronsourceManager shareIronSourceManager] initIronSource];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 默认 IronSource 广告聚合平台初始化成功"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 默认 IronSource 广告聚合平台初始化失败: %@", exception.reason];
        }
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"🎉 广告聚合平台初始化流程完成"];
}


#pragma mark - 日志功能接口实现

+ (void)setLogLevel:(DMLogLevel)level {
    // 将DMLogLevel转换为IMLogLevel
    IMLogLevel imLogLevel;
    switch (level) {
        case DMLogLevelVerbose:
            imLogLevel = IMLogLevelVerbose;
            break;
        case DMLogLevelDebug:
            imLogLevel = IMLogLevelDebug;
            break;
        case DMLogLevelInfo:
            imLogLevel = IMLogLevelInfo;
            break;
        case DMLogLevelWarning:
            imLogLevel = IMLogLevelWarning;
            break;
        case DMLogLevelError:
            imLogLevel = IMLogLevelError;
            break;
        case IMLogLevelOff:
            imLogLevel = IMLogLevelOff;
            break;
        default:
            imLogLevel = IMLogLevelInfo;
            break;
    }
    
    [IMLogUtils setLogLevel:imLogLevel];
    [IMLogUtils info:IMLogTagGeneral format:@"📝 日志级别已设置为: %ld", (long)level];
}

+ (DMLogLevel)currentLogLevel {
    IMLogLevel imLogLevel = [IMLogUtils currentLogLevel];
    
    // 将IMLogLevel转换为DMLogLevel
    switch (imLogLevel) {
        case IMLogLevelVerbose:
            return DMLogLevelVerbose;
        case IMLogLevelDebug:
            return DMLogLevelDebug;
        case IMLogLevelInfo:
            return DMLogLevelInfo;
        case IMLogLevelWarning:
            return DMLogLevelWarning;
        case IMLogLevelError:
            return DMLogLevelError;
        case IMLogLevelOff:
            return IMLogLevelOff;
        default:
            return DMLogLevelInfo;
    }
}

+ (void)enableLog:(BOOL)enable {
    [IMLogUtils enableLog:enable];
    [IMLogUtils info:IMLogTagGeneral format:@"📝 日志功能已%@", enable ? @"启用" : @"禁用"];
}

+ (void)logVerbose:(NSString *)message {
    [IMLogUtils verbose:IMLogTagGeneral format:@"%@", message];
}

+ (void)logDebug:(NSString *)message {
    [IMLogUtils debug:IMLogTagGeneral format:@"%@", message];
}

+ (void)logInfo:(NSString *)message {
    [IMLogUtils info:IMLogTagGeneral format:@"%@", message];
}

+ (void)logWarning:(NSString *)message {
    [IMLogUtils warning:IMLogTagGeneral format:@"%@", message];
}

+ (void)logError:(NSString *)message {
    [IMLogUtils error:IMLogTagGeneral format:@"%@", message];
}

+ (void)enableRealtimeLogPopup {
    [IMLogUtils enableRealtimeLogPopup];
    [IMLogUtils info:IMLogTagGeneral format:@"📱 实时日志弹窗已启用"];
}

+ (void)disableRealtimeLogPopup {
    [IMLogUtils disableRealtimeLogPopup];
    [IMLogUtils info:IMLogTagGeneral format:@"📱 实时日志弹窗已禁用"];
}

+ (NSString *)getLogFilePath {
    NSString *logFilePath = [IMLogUtils currentLogFilePath];
    [IMLogUtils info:IMLogTagGeneral format:@"📄 当前日志文件路径: %@", logFilePath ?: @"无"];
    return logFilePath;
}

+ (NSArray<NSString *> *)getAllLogFilePaths {
    NSArray<NSString *> *logFilePaths = [IMLogUtils allLogFilePaths];
    [IMLogUtils info:IMLogTagGeneral format:@"📄 所有日志文件数量: %lu", (unsigned long)logFilePaths.count];
    return logFilePaths;
}

#pragma mark - UUID管理接口实现

+ (NSString *)getOrCreateLoginUUID {
    NSString *uuid = [IMKeychainUUIDManager getOrCreateLoginUUID];
    [IMLogUtils info:IMLogTagGeneral format:@"🔑 获取或创建登录UUID: %@", uuid ?: @"获取失败"];
    return uuid;
}

+ (void)clearLoginUUID {
    [IMKeychainUUIDManager clearLoginUUID];
    [IMLogUtils info:IMLogTagGeneral format:@"🗑️ 登录UUID已清除"];
}

+ (BOOL)hasLoginUUID {
    BOOL hasUUID = [IMKeychainUUIDManager hasLoginUUID];
    [IMLogUtils info:IMLogTagGeneral format:@"🔍 检查登录UUID存在性: %@", hasUUID ? @"存在" : @"不存在"];
    return hasUUID;
}

#pragma mark - 插屏广告场景化接口实现

- (void)showInterstitialForScene:(NSString *)scene {
    [IMLogUtils info:IMLogTagAd format:@"🎬 展示插屏广告 - 场景: %@", scene ?: @"未指定"];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeInsert]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 插屏广告已被禁用，跳过展示 - 场景: %@", scene];
        return;
    }
    
    if (!scene || scene.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: 场景字符串为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource插屏广告管理器
        DMInterstitialManager *interstitialManager = [DMInterstitialManager shareInterstitialManager];
        [interstitialManager showInterAd:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource插屏广告展示 - 场景: %@", scene];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX插屏广告管理器
        DualMediationMAXInterstitialManager *maxInterstitialManager = [DualMediationMAXInterstitialManager sharedInterstitialManager];
        [maxInterstitialManager showInterAd:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX插屏广告展示 - 场景: %@", scene];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 插屏广告展示失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (BOOL)isInterstitialReadyForScene:(NSString *)scene {
    [IMLogUtils info:IMLogTagAd format:@"🔍 检查插屏广告状态 - 场景: %@", scene ?: @"未指定"];
    
    if (!scene || scene.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: 场景字符串为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    BOOL isReady = NO;
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource插屏广告管理器检查状态
        DMInterstitialManager *interstitialManager = [DMInterstitialManager shareInterstitialManager];
        // IronSource插屏广告管理器暂无状态检查方法，默认返回NO
        isReady = NO;
        [IMLogUtils info:IMLogTagAd format:@"📋 IronSource插屏广告状态 - 场景: %@, 状态: %@", scene, isReady ? @"已准备" : @"未准备"];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX插屏广告管理器检查状态
        DualMediationMAXInterstitialManager *maxInterstitialManager = [DualMediationMAXInterstitialManager sharedInterstitialManager];
        isReady = maxInterstitialManager.isLoadInterstitial;
        [IMLogUtils info:IMLogTagAd format:@"📋 MAX插屏广告状态 - 场景: %@, 状态: %@", scene, isReady ? @"已准备" : @"未准备"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查插屏广告状态失败: 不支持的SDK类型 %@", sdkType];
    }
    
    return isReady;
}

- (void)showInterstitialForSceneEnum:(DMInterstitialScene)scene
                      viewController:(UIViewController *)viewController
                        currentLevel:(NSInteger)currentLevel
                            delegate:(id)delegate {
    [IMLogUtils info:IMLogTagAd format:@"🎬 展示插屏广告 - 场景: %ld, 关卡: %ld", (long)scene, (long)currentLevel];
    
    // 记录关卡信息和代理
    if (delegate) {
        [IMLogUtils info:IMLogTagAd format:@"📋 设置插屏广告代理和关卡信息"];
    }
    
    // 调用基础的场景化接口
    NSString *sceneString = [self stringFromInterstitialScene:scene];
    [self showInterstitialForScene:sceneString];
}

- (void)preloadInterstitialForScene:(DMInterstitialScene)scene {
    NSString *sceneString = [self stringFromInterstitialScene:scene];
    [IMLogUtils info:IMLogTagAd format:@"⏳ 预加载插屏广告 - 场景: %@", sceneString];
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 预加载插屏广告失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource插屏广告管理器预加载
        DMInterstitialManager *interstitialManager = [DMInterstitialManager shareInterstitialManager];
        [interstitialManager loadInterstitial];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource插屏广告预加载 - 场景: %@", sceneString];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX插屏广告管理器预加载
        DualMediationMAXInterstitialManager *maxInterstitialManager = [DualMediationMAXInterstitialManager sharedInterstitialManager];
        [maxInterstitialManager loadInterstitial];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX插屏广告预加载 - 场景: %@", sceneString];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 预加载插屏广告失败: 不支持的SDK类型 %@", sdkType];
    }
}

- (void)showInterAd:(NSString *)adScene {
    // 保留原有接口，调用新的场景化接口
    [self showInterstitialForScene:adScene];
}

#pragma mark - 插屏广告场景转换辅助方法

- (NSString *)stringFromInterstitialScene:(DMInterstitialScene)scene {
    switch (scene) {
        case DMInterstitialSceneLevelWin:
            return @"level_win";
        case DMInterstitialSceneLevelFail:
            return @"level_fail";
        case DMInterstitialSceneLevelRetry:
            return @"retry";
        case DMInterstitialSceneLevelWait:
            return @"waiting";
        default:
            return @"level_win"; // 默认场景
    }
}

#pragma mark - Banner广告重构接口实现

- (void)showBannerAd:(NSString *)sceneValue 
            position:(BannerPosition)position 
enableShortScreenDetection:(BOOL)enableShortScreenDetection {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner广告 - 场景: %@, 位置: %ld, 短屏检测: %@", 
     sceneValue ?: @"未指定", (long)position, enableShortScreenDetection ? @"启用" : @"禁用"];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeBanner]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 Banner广告已被禁用，跳过展示 - 场景: %@", sceneValue];
        return;
    }
    
    if (!sceneValue || sceneValue.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 场景值为空"];
        return;
    }
    
    // 使用DMBannerSceneManager统一管理Banner广告
    [[DMBannerSceneManager sharedManager] showBannerAd:sceneValue position:position enableShortScreenDetection:enableShortScreenDetection];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager展示Banner广告 - 场景: %@", sceneValue];
}

- (void)showBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示场景化Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    // 检查免广告状态
    if ([self isRemoveAd:DMAdBanTypeBanner]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 Banner广告已被禁用，跳过展示 - 场景: %@", sceneName];
        return;
    }
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 场景名称为空"];
        return;
    }
    
    // 使用DMBannerSceneManager统一管理Banner广告
    [[DMBannerSceneManager sharedManager] showBannerForScene:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager展示Banner广告 - 场景: %@", sceneName];
}

- (void)hideBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🙈 隐藏场景化Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: 场景名称为空"];
        return;
    }
    
    // 使用DMBannerSceneManager统一管理Banner广告
    [[DMBannerSceneManager sharedManager] hideBannerForScene:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager隐藏Banner广告 - 场景: %@", sceneName];
}

- (BOOL)isBannerReadyForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🔍 检查场景化Banner广告状态 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: 场景名称为空"];
        return NO;
    }
    
    // 使用DMBannerSceneManager统一管理Banner广告
    BOOL isReady = [[DMBannerSceneManager sharedManager] isBannerReadyForScene:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager检查Banner广告状态 - 场景: %@, 状态: %@", sceneName, isReady ? @"已准备" : @"未准备"];
    
    return isReady;
}

- (void)showBannerForScene:(DMBannerScene)scene
                  position:(DMBannerPosition)position
    enableShortScreenDetection:(BOOL)enableShortScreenDetection
                  delegate:(nullable id<DMAdDelegate>)delegate {
    NSString *sceneString = [self stringFromBannerScene:scene];
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner广告 - 场景: %@, 位置: %ld, 短屏检测: %@", 
     sceneString, (long)position, enableShortScreenDetection ? @"启用" : @"禁用"];
    
    // 设置代理
    if (delegate) {
        [self setAdDelegate:delegate];
        [IMLogUtils info:IMLogTagAd format:@"📋 设置Banner广告代理"];
    }
    
    // 调用基础的场景化接口
    [self showBannerForScene:sceneString];
}

- (void)destroyBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🗑️ 销毁场景化Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告销毁失败: 场景名称为空"];
        return;
    }
    
    // 使用DMBannerSceneManager统一管理Banner广告
    [[DMBannerSceneManager sharedManager] destroyBannerForScene:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager销毁Banner广告 - 场景: %@", sceneName];
}



- (void)preloadBannerForScene:(DMBannerScene)scene {
    NSString *sceneString = [self stringFromBannerScene:scene];
    [IMLogUtils info:IMLogTagAd format:@"⏳ 预加载Banner广告 - 场景: %@", sceneString];
    
    // 使用DMBannerSceneManager统一管理Banner广告
    [[DMBannerSceneManager sharedManager] preloadBannerForScene:sceneString];
    [IMLogUtils info:IMLogTagAd format:@"✅ 通过DMBannerSceneManager预加载Banner广告 - 场景: %@", sceneString];
}

#pragma mark - Banner广告场景转换辅助方法

- (NSString *)stringFromBannerScene:(DMBannerScene)scene {
    switch (scene) {
        case DMBannerSceneInit:
            return @"SCENE_BANNER_INIT";
        case DMBannerSceneLevelEnter:
            return @"SCENE_BANNER_LEVEL_ENTER";
        case DMBannerSceneGameStart:
            return @"SCENE_BANNER_INIT"; // 游戏开始映射到初始化场景
        case DMBannerSceneLevelComplete:
            return @"SCENE_BANNER_LEVEL_WIN";
        case DMBannerSceneLevelFail:
            return @"SCENE_BANNER_LEVEL_FAIL";
        case DMBannerSceneGamePause:
            return @"SCENE_BANNER_GAME_PAUSE";
        case DMBannerSceneMainMenu:
            return @"SCENE_BANNER_MAIN_MENU";
        case DMBannerSceneShop:
            return @"SCENE_BANNER_SHOP";
        case DMBannerSceneSettings:
            return @"SCENE_BANNER_SETTINGS";
        default:
            return @"SCENE_BANNER_INIT"; // 默认场景
    }
}

#pragma mark - Banner广告策略相关私有方法

/**
 * 获取Banner广告策略
 * @param sceneName Banner场景名称
 * @return 策略配置字典
 */
- (NSDictionary *)getBannerStrategyForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"📋 获取Banner广告策略 - 场景: %@", sceneName];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 获取Banner策略失败: 场景名称为空"];
        return @{};
    }
    
    // 使用DMBannerStrategyParser获取真实的策略数据
    DMBannerStrategyParser *strategyParser = [DMBannerStrategyParser sharedParser];
    NSDictionary *strategyConfig = [strategyParser getBannerConfigForScene:sceneName];
    
    if (strategyConfig) {
        [IMLogUtils info:IMLogTagAd format:@"✅ 成功获取Banner策略 - 场景: %@, 配置: %@", sceneName, strategyConfig];
        return strategyConfig;
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 未找到Banner策略配置 - 场景: %@", sceneName];
        return @{};
    }
}

/**
 * 验证Banner策略条件
 * @param strategy 策略配置
 * @param sceneName 场景名称
 * @return 是否满足条件
 */
- (BOOL)validateBannerConditions:(NSDictionary *)strategy forScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"📋 验证Banner广告策略条件 - 场景: %@", sceneName];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 验证Banner策略条件失败: 场景名称为空"];
        return NO;
    }
    
    // 使用DMBannerSceneManager获取当前关卡和展示时间
    DMBannerSceneManager *sceneManager = [DMBannerSceneManager sharedManager];
    NSInteger currentLevel = [sceneManager getCurrentLevel];
    
    // 使用DMBannerStrategyParser进行条件验证
    DMBannerStrategyParser *strategyParser = [DMBannerStrategyParser sharedParser];
    BOOL canShow = [strategyParser canShowBannerScene:sceneName 
                                         currentLevel:currentLevel 
                                         lastShowTime:0]; // 使用0让解析器自己获取上次展示时间
    
    [IMLogUtils info:IMLogTagAd format:@"%@ Banner策略条件验证 - 场景: %@, 关卡: %ld", 
     canShow ? @"✅" : @"❌", sceneName, (long)currentLevel];
    
    return canShow;
}

/**
 * Banner位置枚举转字符串
 * @param position Banner位置枚举
 * @return 位置字符串
 */
- (NSString *)bannerPositionToString:(BannerPosition)position {
    switch (position) {
        case 0: // BannerPositionBottom
            return @"bottom";
        case 1: // BannerPositionTop
            return @"top";
        case 2: // BannerPositionBottomTop
            return @"bottom_top";
        default:
            return @"bottom";
    }
}

#pragma mark - Facebook功能接口实现

- (void)initializeFacebook:(NSString *)appId delegate:(nullable id<DMAdDelegate>)delegate {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 初始化Facebook SDK - AppId: %@", appId];
    
    if (!appId || appId.length == 0) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ Facebook初始化失败: AppId为空"];
        return;
    }
    
    // 设置代理
    if (delegate) {
        self.adDelegate = delegate;
    }
    
    // 调用DMFacebookManager初始化
    // 注意：DMFacebookManager的初始化应该通过initializeWithApplication:launchOptions:方法
    // 这里暂时注释掉，因为该方法不存在
    // [[DMFacebookManager sharedManager] initializeWithAppId:appId];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"✅ Facebook SDK初始化完成"];
}

- (BOOL)handleFacebookURL:(NSURL *)url {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 处理Facebook URL回调: %@", url.absoluteString];
    
    BOOL handled = [DMFacebookManager handleOpenURL:[UIApplication sharedApplication] url:url options:@{}];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"%@ Facebook URL处理结果", handled ? @"✅" : @"❌"];
    
    return handled;
}

- (void)facebookLogin {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 开始Facebook登录"];
    
    DMFacebookManager *facebookManager = [DMFacebookManager sharedManager];
    
    // 使用新的login方法，回调通过DMDelegate机制处理
    [DMFacebookManager login];
}

- (void)facebookLogout {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 Facebook登出"];
    
    [DMFacebookManager logout];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"✅ Facebook登出完成"];
}

- (BOOL)isFacebookLoggedIn {
    BOOL isLoggedIn = [DMFacebookManager isLoggedIn];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"🔍 Facebook登录状态: %@", isLoggedIn ? @"已登录" : @"未登录"];
    
    return isLoggedIn;
}

- (nullable NSString *)getFacebookAccessToken {
    NSString *accessToken = [DMFacebookManager currentAccessToken];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"🔍 获取Facebook访问令牌: %@", accessToken ? @"已获取" : @"无令牌"];
    
    return accessToken;
}

- (void)getFacebookUserInfo {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 获取Facebook用户信息"];
    
    DMFacebookManager *facebookManager = [DMFacebookManager sharedManager];
    
    // 使用新的getUserInfo方法，回调通过DMDelegate机制处理
    [DMFacebookManager getUserInfo];
}

- (nullable NSDictionary *)getCachedFacebookUserInfo {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔍 获取缓存的Facebook用户信息"];
    
    DMFacebookUserInfo *userInfo = [DMFacebookManager getCachedUserInfo];
    
    if (userInfo) {
        NSDictionary *userDict = @{
            @"userId": userInfo.userId ?: @"",
            @"userName": userInfo.name ?: @"",
            @"email": userInfo.email ?: @"",
            @"pictureURL": userInfo.pictureURL ?: @""
        };
        
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 获取缓存用户信息成功 - 用户: %@", userInfo.name];
        
        return userDict;
    } else {
        [IMLogUtils info:IMLogTagSDKInit format:@"ℹ️ 无缓存的Facebook用户信息"];
        
        return nil;
    }
}

- (void)facebookShareLink:(NSString *)url quote:(nullable NSString *)quote {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 Facebook分享链接: %@", url];
    
    if (!url || url.length == 0) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ Facebook分享失败: 链接为空"];
        return;
    }
    
    DMFacebookManager *facebookManager = [DMFacebookManager sharedManager];
    
    // 使用新的shareWithTitle方法，回调通过DMDelegate机制处理
    [DMFacebookManager shareWithTitle:@"" url:url description:quote ?: @""];
}

- (void)facebookShareImage:(UIImage *)image {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 Facebook分享图片"];
    
    if (!image) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ Facebook分享失败: 图片为空"];
        return;
    }
    
    DMFacebookManager *facebookManager = [DMFacebookManager sharedManager];
    
    // 使用新的shareImage方法，回调通过DMDelegate机制处理
    [DMFacebookManager shareImage:image];
}

- (void)setFacebookVerboseLoggingEnabled:(BOOL)enabled {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔵 设置Facebook详细日志: %@", enabled ? @"启用" : @"禁用"];
    
    // setVerboseLoggingEnabled方法在DMFacebookLogger中，而不是DMFacebookManager中
    // [DMFacebookLogger setVerboseLoggingEnabled:enabled];
    // 暂时注释掉，因为需要导入DMFacebookLogger.h
    
    [IMLogUtils info:IMLogTagSDKInit format:@"✅ Facebook详细日志设置完成"];
}
#pragma mark - 免广告设置接口实现

- (void)setRemoveAd:(DMAdBanType)adBanType isRemove:(BOOL)isRemove {
    [IMLogUtils info:IMLogTagAd format:@"🚫 设置免广告状态 - 类型: %ld, 状态: %@", (long)adBanType, isRemove ? @"免广告" : @"正常"];
    
    if (adBanType == DMAdBanTypeAll) {
        // 设置所有广告类型（除激励视频外）
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(DMAdBanTypeInsert) stringValue]];
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(DMAdBanTypeBanner) stringValue]];
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(DMAdBanTypeSplash) stringValue]];
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(DMAdBanTypeNative) stringValue]];
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(DMAdBanTypeAudio) stringValue]];
        
        [IMLogUtils info:IMLogTagAd format:@"✅ 已设置所有广告类型免广告状态（激励视频除外）: %@", isRemove ? @"免广告" : @"正常"];
    } else if (adBanType == DMAdBanTypeReward) {
        // 激励视频不受免广告设置影响
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 激励视频广告不受免广告设置影响，忽略此操作"];
        return;
    } else if (adBanType != DMAdBanTypeUnknown) {
        // 设置单个广告类型
        [self.adBanStatusDict setObject:@(isRemove) forKey:[@(adBanType) stringValue]];
        
        NSString *adTypeName = [self adBanTypeToString:adBanType];
        [IMLogUtils info:IMLogTagAd format:@"✅ 已设置%@免广告状态: %@", adTypeName, isRemove ? @"免广告" : @"正常"];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ 设置免广告失败: 未知的广告类型 %ld", (long)adBanType];
    }
    
    // 持久化存储免广告状态
    [self saveAdBanStatusToDisk];
}

- (BOOL)isRemoveAd:(DMAdBanType)adBanType {
    [IMLogUtils info:IMLogTagAd format:@"🔍 查询免广告状态 - 类型: %ld", (long)adBanType];
    
    if (adBanType == DMAdBanTypeReward) {
        // 激励视频始终不免广告
        [IMLogUtils info:IMLogTagAd format:@"✅ 激励视频广告始终不免广告"];
        return NO;
    } else if (adBanType == DMAdBanTypeAll) {
        // 检查除激励视频外的所有广告类型
        BOOL allRemoved = [self isRemoveAd:DMAdBanTypeInsert] &&
                         [self isRemoveAd:DMAdBanTypeBanner] &&
                         [self isRemoveAd:DMAdBanTypeSplash] &&
                         [self isRemoveAd:DMAdBanTypeNative] &&
                         [self isRemoveAd:DMAdBanTypeAudio];
        
        [IMLogUtils info:IMLogTagAd format:@"✅ 所有广告类型免广告状态: %@", allRemoved ? @"免广告" : @"正常"];
        return allRemoved;
    } else if (adBanType == DMAdBanTypeUnknown) {
        // 未知类型返回默认状态
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 查询未知广告类型，返回默认状态: 正常"];
        return NO;
    } else {
        // 查询单个广告类型
        NSNumber *status = [self.adBanStatusDict objectForKey:[@(adBanType) stringValue]];
        BOOL isRemoved = status ? [status boolValue] : NO;
        
        NSString *adTypeName = [self adBanTypeToString:adBanType];
        [IMLogUtils info:IMLogTagAd format:@"✅ %@免广告状态: %@", adTypeName, isRemoved ? @"免广告" : @"正常"];
        
        return isRemoved;
    }
}

#pragma mark - 免广告辅助方法

/**
 * 广告类型枚举转字符串
 * @param adBanType 广告类型枚举
 * @return 广告类型字符串
 */
- (NSString *)adBanTypeToString:(DMAdBanType)adBanType {
    switch (adBanType) {
        case DMAdBanTypeReward:
            return @"激励视频";
        case DMAdBanTypeInsert:
            return @"插屏广告";
        case DMAdBanTypeBanner:
            return @"Banner广告";
        case DMAdBanTypeSplash:
            return @"开屏广告";
        case DMAdBanTypeNative:
            return @"原生广告";
        case DMAdBanTypeAudio:
            return @"音频广告";
        case DMAdBanTypeAll:
            return @"所有广告";
        case DMAdBanTypeUnknown:
        default:
            return @"未知类型";
    }
}

/**
 * 保存免广告状态到磁盘
 */
- (void)saveAdBanStatusToDisk {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.adBanStatusDict forKey:@"DMAdBanStatusDict"];
    [defaults synchronize];
    
    [IMLogUtils info:IMLogTagAd format:@"💾 免广告状态已保存到磁盘"];
}

/**
 * 从磁盘加载免广告状态
 */
- (void)loadAdBanStatusFromDisk {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *savedStatus = [defaults objectForKey:@"DMAdBanStatusDict"];
    
    if (savedStatus) {
        self.adBanStatusDict = [savedStatus mutableCopy];
        [IMLogUtils info:IMLogTagAd format:@"📂 从磁盘加载免广告状态: %@", savedStatus];
    } else {
        [IMLogUtils info:IMLogTagAd format:@"📂 磁盘中无免广告状态数据，使用默认状态"];
    }
}

#pragma mark - 内购功能接口实现

- (void)acknowledgeInAppPurchaseWithOriginalTransactionId:(NSString *)originalTransactionId
                                          successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                                          failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始核销内购订单 - 交易ID: %@", originalTransactionId];
    
    if (!originalTransactionId || originalTransactionId.length == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 核销失败: 原始交易ID为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" 
                                                 code:1001 
                                             userInfo:@{NSLocalizedDescriptionKey: @"原始交易ID不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    DMInAppVerifyManager *verifyManager = [DMInAppVerifyManager sharedManager];
    [verifyManager acknowledgeInAppPurchaseWithOriginal_transaction_id:originalTransactionId
                                                        successCallback:successCallback
                                                        failureCallback:failureCallback];
}

- (void)fetchUnacknowledgedOrdersWithSuccessCallback:(DMUnacknowledgedOrdersCallback)successCallback
                                      failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始获取未核销订单列表"];
    
    DMInAppVerifyManager *verifyManager = [DMInAppVerifyManager sharedManager];
    [verifyManager fetchUnacknowledgedOrdersWithSuccess:successCallback
                                                 failure:failureCallback];
}

- (void)verifyInAppReceiptWithAppId:(NSString *)appId
                        receiptData:(NSData *)receiptData
                    successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                    failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始校验内购收据 - AppId: %@", appId];
    
    if (!appId || appId.length == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 校验失败: AppId为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" 
                                                 code:1002 
                                             userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    if (!receiptData || receiptData.length == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 校验失败: 收据数据为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" 
                                                 code:1003 
                                             userInfo:@{NSLocalizedDescriptionKey: @"收据数据不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    // 调用DMInAppVerifyManager进行收据校验
    DMInAppVerifyManager *verifyManager = [DMInAppVerifyManager sharedManager];
    [verifyManager verifyInAppReceiptWithAppId:appId
                                   receiptData:receiptData
                               successCallback:successCallback
                               failureCallback:failureCallback];
}

- (void)launchInAppPurchase:(NSString *)productId {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始内购 - 商品ID: %@", productId];
    
    if (!productId || productId.length == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 内购失败: 商品ID为空"];
        return;
    }
    
    // 调用DMInAppPurchaseManager进行内购
    DMInAppPurchaseManager *purchaseManager = [DMInAppPurchaseManager shareInAppPurchaseManager];
    // 确保委托在调用前已正确设置，避免回调丢失
    if (purchaseManager.delegate != self.adDelegate) {
        purchaseManager.delegate = self.adDelegate;
    }
    if (!purchaseManager.delegate) {
        [IMLogUtils info:IMLogTagIAP format:@"ℹ️ IAP委托为空，内购开始回调可能无法触达外部监听者"];
    }
    [purchaseManager launchInAppPurchase:productId];
}

- (void)restoreInAppPurchase:(NSString *)productId {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始恢复购买 - 商品ID: %@", productId];
    
    if (!productId || productId.length == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 恢复购买失败: 商品ID为空"];
        return;
    }
    
    // 调用DMInAppPurchaseManager进行恢复购买
    DMInAppPurchaseManager *purchaseManager = [DMInAppPurchaseManager shareInAppPurchaseManager];
    // 同步设置委托，保证恢复流程回调可达
    if (purchaseManager.delegate != self.adDelegate) {
        purchaseManager.delegate = self.adDelegate;
    }
    if (!purchaseManager.delegate) {
        [IMLogUtils info:IMLogTagIAP format:@"ℹ️ IAP委托为空，恢复购买回调可能无法触达外部监听者"];
    }
    [purchaseManager restoreInAppPurchase:productId];
}

- (void)requestProductsList {
    NSArray<NSString *> *productIds = [[DMConfigReader sharedInstance] allIAPProductIds];

    [IMLogUtils info:IMLogTagIAP format:@"🛒 开始获取商品列表 - 商品ID数组: %@", productIds];
    
    if (!productIds || productIds.count == 0) {
        [IMLogUtils error:IMLogTagIAP format:@"❌ 获取商品列表失败: 商品ID数组为空"];
        return;
    }
    
    // 调用DMProductManager进行商品列表获取
    DMProductManager *productManager = [DMProductManager sharedManager];
    // 确保委托设置，便于商品列表回调触达
    if (productManager.delegate != self.adDelegate) {
        productManager.delegate = self.adDelegate;
    }
    [productManager requestProductsWithIdentifiers:productIds];
}

#pragma mark -------adjsut 事件上报 --------

- (void)trackAdjustEvent:(NSString *)eventId {
    [[DMAdjustManager sharedManager]trackAdjustEvent:eventId];
}

#pragma mark - 数数 SDK 事件上报接口实现

- (void)thinkingSetSuperPropertiesJsonStr:(id)jsonStr {
    [IMLogUtils info:IMLogTagAPI format:@"🧠 设置数数公共属性"]; 
    [[DMThinkingManager sharedManager] thinkingSetSuperPropertiesJsonStr:jsonStr];
}

- (void)thinkingTrackEventWithKey:(NSString *)key jsonStr:(id)jsonStr {
    [IMLogUtils info:IMLogTagAPI format:@"🧠 上报数数事件: %@", key ?: @"<nil>"];
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:key jsonStr:jsonStr];
}

- (void)thinkingTrackUserPropertiesJsonStr:(id)jsonStr {
    [IMLogUtils info:IMLogTagAPI format:@"🧠 设置数数用户属性(JSON)"];
    [[DMThinkingManager sharedManager] thinkingTrackUserPropertiesJsonStr:jsonStr];
}

- (void)thinkingUser_setOnceWithKey:(NSString *)key value:(NSString *)value {
    [IMLogUtils info:IMLogTagAPI format:@"🧠 设置数数用户属性(once): %@", key ?: @"<nil>"];
    [[DMThinkingManager sharedManager] thinkingUser_setOnceWithKey:key value:value];
}

#pragma mark - 关卡事件埋点接口实现

+ (void)SDK_Level_Start:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡开始埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelStart:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡开始埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡开始埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Win:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡胜利埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelWin:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡胜利埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡胜利埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Lose:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡失败埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelFail:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡失败埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡失败埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Enter:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡进入埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelEnter:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡进入埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡进入埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Revive:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡复活埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelRevive:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡复活埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡复活埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Retry:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡重试埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelRetry:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡重试埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡重试埋点异常: %@", exception.reason];
        }
    });
}

+ (void)SDK_Level_Prop:(NSInteger)level {
    [IMLogUtils info:IMLogTagSDKInit format:@"🎮 关卡道具埋点 - 关卡: %ld", (long)level];
    
    // 异步执行埋点，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [[DMThinkingManager sharedManager] thinkingTrackLevelProp:level];
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡道具埋点成功 - 关卡: %ld", (long)level];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡道具埋点异常: %@", exception.reason];
        }
    });
}

#pragma mark - 测试接口实现

+ (void)runLevelEventTrackingTests {
    [IMLogUtils info:IMLogTagSDKInit format:@"🧪 开始运行关卡事件埋点测试"];
    
    // 异步执行测试，避免阻塞主线程
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ 关卡事件埋点测试完成"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 关卡事件埋点测试异常: %@", exception.reason];
        }
    });
}

#pragma mark - iOS标准生命周期方法实现

- (BOOL)applicationDidFinishLaunching:(UIApplication *)application withOptions:(nullable NSDictionary *)launchOptions {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 🚀 应用启动完成"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    return [lifecycleManager applicationDidFinishLaunching:application withOptions:launchOptions];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] ✨ 应用变为活跃状态"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationDidBecomeActive:application];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 💤 应用将要失去活跃状态"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 🌙 应用进入后台"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] ☀️ 应用将要进入前台"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationWillEnterForeground:application];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 🛑 应用将要终止"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationWillTerminate:application];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] ⚠️ 应用收到内存警告"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationDidReceiveMemoryWarning:application];
}

- (void)applicationDidReceiveRemoteNotification:(UIApplication *)application userInfo:(NSDictionary *)userInfo {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 📬 应用收到远程推送通知"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationDidReceiveRemoteNotification:application userInfo:userInfo];
}

- (void)applicationDidReceiveLocalNotification:(UIApplication *)application notification:(UILocalNotification *)notification {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 📮 应用收到本地通知"];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    [lifecycleManager applicationDidReceiveLocalNotification:application notification:notification];
}

- (BOOL)applicationOpenURL:(UIApplication *)application url:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 🔗 应用打开URL: %@", url.absoluteString];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    return [lifecycleManager applicationOpenURL:application url:url options:options];
}

- (BOOL)applicationContinueUserActivity:(UIApplication *)application userActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * _Nullable restorableObjects))restorationHandler {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DualMediationSDKPublic] 🔄 应用继续用户活动: %@", userActivity.activityType];
    
    // 将生命周期事件转发给DMLifecycleManager处理
    DMLifecycleManager *lifecycleManager = [DMLifecycleManager sharedManager];
    return [lifecycleManager applicationContinueUserActivity:application userActivity:userActivity restorationHandler:restorationHandler];
}

#pragma mark - 实时日志窗口接口实现

- (void)showRealTimeLogWindow {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 显示实时日志窗口"];
    
    if (!self.realTimeLogWindow) {
        // 获取主窗口（优先选择正常层级的keyWindow，避免选中悬浮窗自身）
        UIWindow *targetWindow = nil;
        if (@available(iOS 13.0, *)) {
            for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
                if (scene.activationState != UISceneActivationStateForegroundActive) { continue; }
                if (![scene isKindOfClass:[UIWindowScene class]]) { continue; }
                UIWindowScene *windowScene = (UIWindowScene *)scene;

                // 1) keyWindow 且 normal 层级
                for (UIWindow *w in windowScene.windows) {
                    if (!w.isHidden && w.isKeyWindow && w.windowLevel == UIWindowLevelNormal) {
                        targetWindow = w; break;
                    }
                }
                if (targetWindow) break;

                // 2) 任意 normal 层级窗口
                for (UIWindow *w in windowScene.windows) {
                    if (!w.isHidden && w.windowLevel == UIWindowLevelNormal) {
                        targetWindow = w; break;
                    }
                }
                if (targetWindow) break;

                // 3) 兜底：任何可见窗口（排除我们自己的悬浮窗）
                for (UIWindow *w in windowScene.windows) {
                    if (!w.isHidden && w != self.floatingLogWindow) {
                        targetWindow = w; break;
                    }
                }
                if (targetWindow) break;
            }
        }
        if (!targetWindow) {
            // 旧系统或兜底
            for (UIWindow *w in [UIApplication sharedApplication].windows) {
                if (!w.isHidden && w.isKeyWindow && w.windowLevel == UIWindowLevelNormal) { targetWindow = w; break; }
            }
            if (!targetWindow) {
                for (UIWindow *w in [UIApplication sharedApplication].windows) {
                    if (!w.isHidden && w.windowLevel == UIWindowLevelNormal) { targetWindow = w; break; }
                }
            }
            if (!targetWindow) {
                targetWindow = [UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject;
            }
        }
        
        if (!targetWindow) {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ 无法获取主窗口，实时日志窗口显示失败"];
            return;
        }
        
        // 创建实时日志窗口并设置frame
        self.realTimeLogWindow = [[RealTimeLogWindow alloc] initWithFrame:targetWindow.bounds];
        
        // 添加到主窗口
        [targetWindow addSubview:self.realTimeLogWindow];
        __weak typeof(self) weakSelf = self;
        self.realTimeLogWindow.onClose = ^{
            // 关闭日志窗口后恢复悬浮按钮显示
            if (weakSelf.floatingLogWindow) {
                weakSelf.floatingLogWindow.hidden = NO;
            }
        };
    }
    
    // 显示日志窗口时隐藏悬浮按钮，避免遮挡
    if (self.floatingLogWindow) {
        self.floatingLogWindow.hidden = YES;
    }

    [self.realTimeLogWindow show];
}

- (void)hideRealTimeLogWindow {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 隐藏实时日志窗口"];
    
    if (self.realTimeLogWindow) {
        [self.realTimeLogWindow hide];
        // 从父视图中移除
        [self.realTimeLogWindow removeFromSuperview];
        self.realTimeLogWindow = nil;
        // 恢复悬浮按钮
        if (self.floatingLogWindow) {
            self.floatingLogWindow.hidden = NO;
        }
    }
}

- (BOOL)isRealTimeLogWindowVisible {
    if (!self.realTimeLogWindow) {
        return NO;
    }
    return [self.realTimeLogWindow isVisible];
}

- (void)enableRealTimeLogMonitoring:(BOOL)enable {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 %@实时日志监听", enable ? @"启用" : @"禁用"];
    
    if (!self.realTimeLogWindow) {
        self.realTimeLogWindow = [[RealTimeLogWindow alloc] init];
    }
    
    [self.realTimeLogWindow enableIMLogMonitoring:enable];
}

- (void)setRealTimeLogMinimumLevel:(NSInteger)minLevel {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 设置实时日志最小级别: %ld", (long)minLevel];
    
    if (!self.realTimeLogWindow) {
        self.realTimeLogWindow = [[RealTimeLogWindow alloc] init];
    }
    
    [self.realTimeLogWindow setMinimumLogLevel:(IMLogLevel)minLevel];
}

- (void)setRealTimeLogVisibleTags:(nullable NSArray<NSNumber *> *)tags {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 设置实时日志可见标签: %@", tags];
    
    if (!self.realTimeLogWindow) {
        self.realTimeLogWindow = [[RealTimeLogWindow alloc] init];
    }
    
    [self.realTimeLogWindow setVisibleLogTags:tags];
}

- (void)clearRealTimeLogWindow {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 清除实时日志窗口内容"];
    
    if (self.realTimeLogWindow) {
        [self.realTimeLogWindow clearLogs];
    }
}

- (void)exportRealTimeLogsWithSystemLogs:(BOOL)includeSystemLogs 
                              completion:(nullable void(^)(NSString * _Nullable filePath, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 导出实时日志，包含系统日志: %@", includeSystemLogs ? @"是" : @"否"];
    
    if (!self.realTimeLogWindow) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"DualMediationSDK" 
                                               code:-1 
                                           userInfo:@{NSLocalizedDescriptionKey: @"实时日志窗口未初始化"}];
            completion(nil, error);
        }
        return;
    }
    
    [self.realTimeLogWindow exportLogsWithSystemLogs:includeSystemLogs completion:completion];
}

- (NSDictionary *)getRealTimeLogStatistics {
    if (!self.realTimeLogWindow) {
        return @{};
    }
    
    return [self.realTimeLogWindow getLogStatistics];
}

- (void)setRealTimeLogFormat:(BOOL)showTimestamp
                   showLevel:(BOOL)showLevel
                     showTag:(BOOL)showTag
                  showThread:(BOOL)showThread {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 设置实时日志格式 - 时间戳:%@ 级别:%@ 标签:%@ 线程:%@", 
     showTimestamp ? @"是" : @"否", 
     showLevel ? @"是" : @"否", 
     showTag ? @"是" : @"否", 
     showThread ? @"是" : @"否"];
    
    if (!self.realTimeLogWindow) {
        self.realTimeLogWindow = [[RealTimeLogWindow alloc] init];
    }
    
    [self.realTimeLogWindow setLogFormat:showTimestamp 
                                showLevel:showLevel 
                                  showTag:showTag 
                               showThread:showThread];
}

- (void)searchRealTimeLogs:(NSString *)keyword caseSensitive:(BOOL)caseSensitive {
    [IMLogUtils info:IMLogTagSDKInit format:@"📊 搜索实时日志关键词: %@，大小写敏感: %@", keyword, caseSensitive ? @"是" : @"否"];
    
    if (!self.realTimeLogWindow) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"📊 实时日志窗口未初始化，无法搜索"];
        return;
    }
    
    [self.realTimeLogWindow searchLogs:keyword caseSensitive:caseSensitive];
}

#pragma mark - 实时日志悬浮按钮实现

- (void)showFloatingLogButton {
    if (self.floatingLogWindow) {
        self.floatingLogWindow.hidden = NO;
        return;
    }

    UIWindowScene *activeScene = nil;
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) {
                activeScene = (UIWindowScene *)scene;
                break;
            }
        }
    }

    // 创建悬浮窗
    if (@available(iOS 13.0, *)) {
        self.floatingLogWindow = [[_DMPassthroughWindow alloc] initWithWindowScene:activeScene];
        self.floatingLogWindow.frame = [UIScreen mainScreen].bounds;
    } else {
        self.floatingLogWindow = [[_DMPassthroughWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    self.floatingLogWindow.backgroundColor = [UIColor clearColor];
    self.floatingLogWindow.windowLevel = UIWindowLevelStatusBar + 1;
    self.floatingLogWindow.hidden = NO;

    // 简单根控制器，承载按钮
    UIViewController *rootVC = [[UIViewController alloc] init];
    rootVC.view.backgroundColor = [UIColor clearColor];
    self.floatingLogWindow.rootViewController = rootVC;

    // 创建按钮
    CGFloat size = 56.0;
    self.floatingLogButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.floatingLogButton.frame = CGRectMake(CGRectGetWidth(self.floatingLogWindow.bounds) - size - 12,
                                              CGRectGetHeight(self.floatingLogWindow.bounds) * 0.6,
                                              size,
                                              size);
    self.floatingLogButton.backgroundColor = [UIColor colorWithRed:0.38 green:0.22 blue:0.73 alpha:0.95];
    [self.floatingLogButton setTitle:@"📊" forState:UIControlStateNormal];
    [self.floatingLogButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.floatingLogButton.titleLabel.font = [UIFont systemFontOfSize:28 weight:UIFontWeightSemibold];
    self.floatingLogButton.layer.cornerRadius = size/2.0;
    self.floatingLogButton.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.35].CGColor;
    self.floatingLogButton.layer.shadowOpacity = 0.6;
    self.floatingLogButton.layer.shadowOffset = CGSizeMake(0, 3);
    self.floatingLogButton.layer.shadowRadius = 6;
    self.floatingLogButton.accessibilityLabel = @"实时日志悬浮按钮";

    [self.floatingLogButton addTarget:self action:@selector(_dm_floatingLogButtonTapped) forControlEvents:UIControlEventTouchUpInside];

    // 拖拽手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(_dm_handleFloatingPan:)];
    [self.floatingLogButton addGestureRecognizer:pan];

    [rootVC.view addSubview:self.floatingLogButton];
    self.floatingLogWindow.hitTestView = self.floatingLogButton; // 仅按钮可响应，其余透传
}

- (void)hideFloatingLogButton {
    if (self.floatingLogWindow) {
        self.floatingLogWindow.hidden = YES;
    }
}

- (BOOL)isFloatingLogButtonVisible {
    return self.floatingLogWindow && !self.floatingLogWindow.hidden;
}

#pragma mark - 悬浮按钮事件

- (void)_dm_floatingLogButtonTapped {
    // 点击切换日志窗口显示/隐藏
    if ([self isRealTimeLogWindowVisible]) {
        [self hideRealTimeLogWindow];
    } else {
        [self showRealTimeLogWindow];
        // 默认开启IMLogUtils监听
        [self enableRealTimeLogMonitoring:YES];
    }
}

- (void)_dm_handleFloatingPan:(UIPanGestureRecognizer *)pan {
    UIView *button = pan.view;
    UIView *container = self.floatingLogWindow.rootViewController.view;
    CGPoint translation = [pan translationInView:container];

    if (pan.state == UIGestureRecognizerStateBegan) {
        self.floatingButtonInitialCenter = button.center;
    }

    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint newCenter = CGPointMake(self.floatingButtonInitialCenter.x + translation.x,
                                        self.floatingButtonInitialCenter.y + translation.y);
        // 约束在屏幕内
        CGFloat halfW = CGRectGetWidth(button.bounds)/2.0;
        CGFloat halfH = CGRectGetHeight(button.bounds)/2.0;
        CGFloat maxX = CGRectGetWidth(container.bounds) - halfW - 2;
        CGFloat maxY = CGRectGetHeight(container.bounds) - halfH - 2;
        newCenter.x = MAX(halfW + 2, MIN(maxX, newCenter.x));
        newCenter.y = MAX(halfH + 2, MIN(maxY, newCenter.y));
        button.center = newCenter;
    }

    if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) {
        // 吸附到最近边缘
        CGFloat midX = CGRectGetMidX(container.bounds);
        CGFloat targetX = (button.center.x < midX) ? (CGRectGetWidth(button.bounds)/2.0 + 8) : (CGRectGetWidth(container.bounds) - CGRectGetWidth(button.bounds)/2.0 - 8);
        [UIView animateWithDuration:0.25 animations:^{
            button.center = CGPointMake(targetX, button.center.y);
        }];
    }
}

#pragma mark - Firebase Analytics 事件上报接口实现

- (void)logFirebaseEvent:(NSString *)eventName parameters:(nullable NSDictionary<NSString *, id> *)parameters {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔥 Firebase事件上报: %@, 参数: %@", eventName, parameters];
    
    if (!eventName || eventName.length == 0) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ Firebase事件名称不能为空"];
        return;
    }
    
    // 调用DMFirebaseManager的事件上报方法
    [[DMFirebaseManager shareFirebaseManager] logEvent:eventName parameters:parameters];
}

- (void)logFirebaseEvent:(NSString *)eventName 
              parameters:(nullable NSDictionary<NSString *, id> *)parameters 
              completion:(nullable void(^)(NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔥 Firebase事件上报(带回调): %@, 参数: %@", eventName, parameters];
    
    if (!eventName || eventName.length == 0) {
         [IMLogUtils error:IMLogTagSDKInit format:@"❌ Firebase事件名称不能为空"];
         if (completion) {
             NSError *error = [NSError errorWithDomain:@"DualMediationSDK" 
                                                code:-1 
                                            userInfo:@{NSLocalizedDescriptionKey: @"事件名称不能为空"}];
             completion(error);
         }
         return;
     }
    
    // 调用DMFirebaseManager的带回调事件上报方法
    [[DMFirebaseManager shareFirebaseManager] logEvent:eventName parameters:parameters completion:completion];
}

- (void)setFirebaseUserProperty:(nullable NSString *)value forName:(NSString *)name {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔥 Firebase设置用户属性: %@ = %@", name, value];
    
    if (!name || name.length == 0) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ Firebase用户属性名称不能为空"];
        return;
    }
    
    // 调用DMFirebaseManager的设置用户属性方法
    [[DMFirebaseManager shareFirebaseManager] setUserProperty:value forName:name];
}

- (void)setFirebaseUserId:(nullable NSString *)userId {
    [IMLogUtils info:IMLogTagSDKInit format:@"🔥 Firebase设置用户ID: %@", userId];
    
    // 调用DMFirebaseManager的设置用户ID方法
    [[DMFirebaseManager shareFirebaseManager] setUserId:userId];
}

#pragma mark - 应用信息界面接口实现

- (void)showAppInfoViewController:(UIViewController *)viewController {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 显示应用信息界面"];
    
    if (!viewController) {
        [IMLogUtils error:IMLogTagSDKInit format:@"❌ 视图控制器不能为空"];
        return;
    }
    
    AppInfoViewController *appInfoVC = [[AppInfoViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:appInfoVC];
    // 以页面表单样式展示，接近截图中的半框弹窗
    navController.modalPresentationStyle = UIModalPresentationPageSheet;
    if (@available(iOS 15.0, *)) {
        UISheetPresentationController *sheet = navController.sheetPresentationController;
        if (sheet) {
            sheet.detents = @[[UISheetPresentationControllerDetent mediumDetent],
                               [UISheetPresentationControllerDetent largeDetent]];
            sheet.prefersGrabberVisible = YES;
            sheet.preferredCornerRadius = 20.0;
        }
    }
    
    [viewController presentViewController:navController animated:YES completion:^{
        [IMLogUtils info:IMLogTagSDKInit format:@"✅ 应用信息界面已打开"];
    }];
}

#pragma mark - 网络状态（对外可用）

/**
 开始监听网络状态变化
 @param callback 网络状态变化回调（可为 nil，仅用通知）
 */
+ (void)startNetworkMonitoringWithCallback:(void (^_Nullable)(DMNetworkStatus status))callback {
    [[DMNetworkMonitor sharedManager]setNetworkStatusChanged:callback];
}

/** 停止监听网络状态变化 */
+ (void)stopNetworkMonitoring {
    [[DMNetworkMonitor sharedManager]stopMonitoring];
}

@end
